Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create sub category using jquery ajax when selecting a category in Django
I have a problem that when I select a category, sub categories are not showing or showing default option only. I want to show sub-categories about what the user category selected. This is my html code <div class="container pt-5" style="height: 800px !important;"> <div class="mx-auto" style="width: 500px" ;> <form id="form" action="../message/" method="post" name="contactForm" class="form-horizontal" data-subCat-url="{% url 'ajax_load_subCats' %}"> {% csrf_token%} <div class="col-xs-8 col-xs-offset-4 mt-5"> <h2 style="text-align:center;">Contact</h2> </div> <div class="form-group"> <label class="p-2" for="title">Title</label> <input type="title" class="form-control" name="text" id="title" placeholder="Enter A Title" required="required"> </div> <div class="form-group"> <label class="p-2" for="category">Category</label> <select class="form-select" aria-label="Default select example" id="category" required> <option selected>Select a category</option> <option value="theft">Theft</option> <option value="assault">Assault</option> <option value="accident">Accident</option> <option value="fire">Fire</option> </select> </div> <div class="form-group"> <label class="p-2" for="category">Sub Category</label> <select id="subCat" class="form-select" aria-label="Default select example" required> </select> </div> <div class="form-group"> <label class="p-2" for="subject">Subject</label> <textarea type="text" class="form-control" name="subject" cols="30" rows="10" placeholder="Enter Subject" required="required"></textarea> </div> <button type="submit" class="btn btn-primary float-end mt-2">Send</button> <br /> <div class="form-group"> {% for message in messages %} <div class="alert alert-danger" role="alert"> {{message}} </div> {% endfor %} </div> </form> </div> </div> I didn't add html tags like body, head, html, so the problem is not there. This is my Jquery script $(document).ready(function(){ $("#category").change(function(){ const url = $("#form").attr('data-subCat-url'); const catName = $(this).children("option:selected").val(); console.log(url) console.log(catName) $.ajax({ url: … -
How to use some variable that call a function to put inside of HTML template in DJANGO
I need to use that function below, here is in util.py try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None ``` Then I put that in my views.py with the var "get" def getFunction(request): return render(request, "encyclopedia/index.html", { "get": util.get_entry() }) So I want to use that function in my index.html {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <a href="{% get %}"><li>{{ entry }}</li></a> //{% get %} doesn't work {% endfor %} </ul> {% endblock %} The only for is to show up a list with 5 items and inside of li, using entry I can display all five items (e.g: apple, banana, tomato, pear, grape) I need to use href because When I click it will to another folder/file .md that will be writed about apple for example I wanna use that function to take in my file .md If you need more informations just ask me. thank u. :) -
Get url param in django
I have this view: @login_required def newAnswer(request, id): post = Post.objects.get(id=id) form = AnswerForm(request.POST) if request.method == 'POST': if form.is_valid(): obj = form.save(commit=False) obj.author = request.user obj.post = post obj.save() form.save_m2m() return redirect('main:post', id=post.id) else: return render(request, 'main/newAnswer.html', { 'form': form, 'formErrors': form.errors, 'userAvatar': getAvatar(request.user)}) else: return render(request, 'main/newAnswer.html', {'form': form, 'post': post, 'userAvatar': getAvatar(request.user)}) When i try to post without loging in, it redirects me to "/accounts/login?next=/post/answer/new/81". My question is how can i get the "next" param in my login view thanks! -
Using a websocket to send messages between two users, but only one user is sending
Highlevel I would like to redirect pairs of users to different rooms. Implementation I am doing this by connecting both matched users to a websocket. Upon connecting each user should send a message to the other user along with the roomID that I will be redirecting the users to. The current issue is that only the user who connects to the websocket last sends a message to the first user and not vice versa Desired Action This is the desired action UserA connects to the websocket UserB connects to the websocket UserA sends back to UserB, UserB's user_id, along with the roomID UserB sends back to UserA, UserA's user_id, along with the roomID This is what is currently happening UserA connects to the websocket UserB connects to the websocket UserB sends back to UserA, UserA's user_id, along with the roomID Here is my frontend code: ... connect() { const args = JSON.parse(localStorage.getItem('authTokens')) const queryString = args.refresh const path = `ws://127.0.0.1:8000/connect/testing/?${queryString}`; this.socketRef = new WebSocket(path); this.socketRef.onopen = (data) => { console.log('WebSocket open'); } this.socketRef.onerror = e => { console.log(e); }; } async sendData(data){ if(this.socketRef.readyState !== WebSocket.OPEN) { console.log('we are still waiting') this.socketRef.onopen = () => this.socketRef.send(data); const socketResp = await new … -
Null value in column "user_id" of relation "authentication_junioruser" violates not-null constraint
I'm trying to do POST request and getting error: IntegrityError at /accounts/juniorprofile/ null value in column "user_id" of relation "authentication_junioruser" violates not-null constraint DETAIL: Failing row contains (14, Ms K, Vadim, t, 99999999, , null, , 2022-10-23, , DevOps, , , set(), , null, null). Junior User is inherited from the custom User model class ListCreateUserProfile(generics.ListCreateAPIView): queryset = JuniorUser.objects.all() serializer_class = JuniorProfileSerializer views.py class JuniorProfileSerializer(serializers.ModelSerializer): location = LocationSerializer(read_only=True, many=True) language = serializers.MultipleChoiceField(choices=LANGUAGE) work_experience = ExperienceSerializer(read_only=True, many=True) education = EducationSerializer(read_only=True, many=True) course = CourseSerializer(read_only=True, many=True) class Meta: model = JuniorUser fields = ['id', 'terms_is_accepted', 'first_name', 'last_name', 'phone_number', 'telegram_nick', 'linkedin', 'location', 'profile_photo', 'date_of_birth', 'specialization', 'hard_skills', 'soft_skills', 'language', 'work_experience', 'education', 'course', 'other_info', 'portfolio_link'] serializers.py class JuniorUser(models.Model): """ This model points to an instance of User model and expands that one to determine the role of Junior User. All the class attributes was got from the technical requirements 'Registration form' """ user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="junior") first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) ... def __str__(self): return str(self.user) if self.user else '' models.py -
Social Network Login Failure For Twitter
I'm trying to integrate Django Social Authentication for Twitter everything is working fine but when I click to login with twitter it redirecting me to a page saying. Redirecting you back to the application. This may take a few moments. After that... Social Network Login Failure An error occurred while attempting to login via your social network account. Login with twitter page Social Network Login Failure page Social Network Login Failure PAGE URL: http://127.0.0.1:8000/accounts/twitter/login/callback/?oauth_token=2iC_EQAAAAABhMevAAABg4CH1lM&oauth_verifier=Yo9Yd8uuASo92R06tDU8dmoLf8fWawje what's wrong here CORRECT me! -
Django getting data in my template from session(dictionary)
how do I get the other itens from my session in django and im passing the session as a dictionary in my cart_page.html my session: {'3': {'quantity': 1, 'price': 4.0, 'totalitem': '4.00'}, '1': {'quantity': 1, 'price': 30.0, 'totalitem': '30.00'}} view.py: return render(request, 'cart/cart_page.html', {'itens': itens}) but when I do: {% for item in itens %} {{item}} {% endfor %} in my {{item}} it only has 3 and 1, how to I get the quantity and price inside it? -
Django Multiple Form on same page interact with each other
I have a page with two forms. When I click on the button Update Profile on the left Form it also send the POST request to the the second form which is not what I want. I don't want them to interact together. How can I do that? views.py @login_required(login_url='signin') def dashboard(request): global user_id data = Account.objects.filter(user=request.user) profile_data = Profile.objects.get(user=request.user) profile_form = ProfileForm(request.POST or None, instance=profile_data) addaccount_form = AddAccountForm(request.POST or None) # Update Profile Settings if profile_form.is_valid(): print("worked") profile_form.save() if request.method == "POST": if addaccount_form.is_valid(): # save account to DataBase return HttpResponseRedirect("http://127.0.0.1:7000/dashboard/") context = { 'data': data, 'profile_form': profile_form, 'addaccount_form': addaccount_form, } return render(request, "main/dashboard.html", context) dashboard.html <form action="" method="POST"> {% csrf_token %} {{profile_form}} <button type="submit" class="updatebut">Update Profile</button> </form> <form action="" method="POST"> {% csrf_token %} {{addaccount_form}} <button type="submit" class="addbut">Add Account</button> </form> -
How do I save my Gist script tag in Ckeditor?
Quick question. I try to post the script to a Gist in Ckeditor, in my Django website. Whenever I post the < script > in the editor, it just shows up as raw code. My work around for this was editing the raw file, inserting the < script >. Which worked, except for some reason if I need to alter anything else in the code I have to reinsert it again. Any workaround for this? I was using the codeblocks feature of ckeditor, but I like the formatting of embedded gists better because it shows line numbers, etc. -
request.data is different in runserver and uwsgi
I'm sending a post request to server. I use runserver to test and I use uwsgi inside docker as well. When I use request.data to serialize the object, it works fine in run server. The output data is like [enter image description here][1] But when I use uwsgi in docker-omposer up and use the same request.data it is different. This causes it not to store in DB. [enter image description here][2] Can someone explain what is wrong here? Thanks [1]: https://i.stack.imgur.com/oFVpz.png [2]: https://i.stack.imgur.com/T6sIf.png -
Gunicorn is stuck in deadlock for python django service running in docker container
I am running a python django webhook application that runs via gunicorn server. My setup is nginx + Gunicorn + Django. Here is what the config looks like: gunicorn app1.wsgi:application --bind 0.0.0.0:8000 --timeout=0 The application runs perfectly for ~1 -2 million request, but after running for few hours the gunicorn shows in sleep state and then no more webhook event gets received root 3219 1.3 0.0 256620 61532 ? Sl 14:04 0:19 /usr/local/bin/python /usr/local/bin/gunicorn app1.wsgi:application --bind 0.0.0.0:8000 --timeout=0 The service is running in 4 different containers and within few hours this behavior is observed for 1 container and then it occurs for one or more containers in subsequent hours. I tried sending a signal to reload gunicorn config which is able to bring the gunicorn process into running state. What is curious is that when I run 4 django containers, for few requests it works perfectly well. But continuously receiving traffic causes this deadlock in one of the gunicorn worker's state and it keep on waiting for a trigger to start accepting traffic again while rest of the three gunicorn workers are healthy and running ! Question - Why does gunicorn worker process is going in sleep state(Sl)? How can … -
Docker and Django Postgresql issue
I am currently learning how to implement docker with Django and Postgres DB. Everytime I tried I run the following command: docker compose up --build -d --remove-orphans Although I can see all my images are started. Every time I tried to open my Django admin site, I cannot sign in using already registered superuser credentials. In Postgres DB PGAdmin all the data that are created previously are stored and saved correctly. But after closing my computer an I start Docker compose up previously saved data's are not recognized by the new start up even if the data still visible in my Postgres DB. How can I make the data to be recognized at start up? Here is my docker-compose.yml configurations: version: "3.9" services: api: build: context: . dockerfile: ./docker/local/django/Dockerfile # ports: # - "8000:8000" command: /start volumes: - .:/app - ./staticfiles:/app/staticfiles - ./mediafiles:/app/mediafiles expose: - "8000" env_file: - .env depends_on: - postgres-db - redis networks: - estate-react client: build: context: ./client dockerfile: Dockerfile.dev restart: on-failure volumes: - ./client:/app - /app/node_modules networks: - estate-react postgres-db: image: postgres:12.0-alpine ports: - "5432:5432" volumes: - ./postgres_data:/var/lib/postgresql environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} networks: - estate-react redis: image: redis:5-alpine networks: - estate-react celery_worker: build: … -
Django, Postman. Why the GET request doesn't respond with my API?
I am developing on my local and try to get view (non-programming term) of my API. My view (programming term) is simply looks like: class WeaponDetailsView(DetailView): model = Weapon template_name = 'weapons/weapon/details.html' I also try to get response via script: import requests url = 'http://127.0.0.1:8000/' res = requests.get(url).json() print(res) But this gives me the raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) requests.exceptions.JSONDecodeError: Expecting value: line 2 column 1 (char 1) error. So why can't I see my APIs only, and not the html body content? And why the situation changes when I implement an API View with Django Rest Framework? I mean it returns only APIs which is grate -
How to plot Django data on a Chart.js graph?
I am so tilted, so so so tilted. Been trying to work chart.js for a while now on my website I built with Django. I want to plot two fields: Dates and Scores. Dates is a date such as 1/6/2022, score is a float. My issue is that when I pass through the python list to the script it pretends it's something disgusting. But when I copy and past the list and put it into the chart's data it's fine. It only doesn't work when it thinks it's a variable which just makes no sense at all and I can't find anywhere that is talking about this. views.py def progress(response): lessons = StudentLessons.objects.get(name=response.user.email) scores = [] dates = [] for lesson in lessons.lesson_set.all(): dates.append(str(lesson.date)) scores.append(str((lesson.accuracy+lesson.speed+lesson.understanding)/3)) context = { 'dates':dates, 'scores':scores, } return render(response, "main/progress.html", context) dates = ['2022-09-27', '2022-09-28'] scores = ['4.333333333333333', '6.0'] (from console) html that displays the correct chart <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <canvas id="myChart" style="width:100%;max-width:700px"></canvas> <script type="text/javascript"> var myChart = new Chart("myChart",{ type:"line", data: { labels: ['2022-09-27', '2022-09-28'], datasets:[{ borderColor: "rgba(0,0,0,0.1)", data: ['4.333333333333333', '6.0'] }] }, options:{ responsive: true, legend: { position: 'top', }, } }); </script> html that doesn't work <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <canvas id="myChart" style="width:100%;max-width:700px"></canvas> <script type="text/javascript"> var … -
Table generating for web
I have a web app made in django which generates a school timetable. It takes around 5-10 minutes to generate one because it is for 25 classes with a lot of links to every teacher and class with separate timetables. I want to rewrite the whole app and if it's possible I want to make it run faster. I can use django and plain html/js/php. What should I use for this kind of problem or does it even matter if I don't use django or if there is a better framework for this beside these two. -
Is there a way to have an action with detail = True inside another action with detail = True in Django rest?
My user model has a Many to one relationship to a Clothes model and inside my User viewset I created an extra action to list the Clothes instances in relation to a specific user @action(detail=True, methods=['get'], serializer_class=UserOutfitSerializer) def outfit (self, request, pk=None): user = User.objects.get(id=pk) clothes = user.clothes_set.all() serializer = UserOutfitSerializer(user.clothes_set.all(), many=True) return Response(serializer.data, status=status.HTTP_200_OK) It's possible to make another extra action to retrive/update/delete each instance clothes for that user ('http://127.0.0.1:8000/api/users/user_id/outfit/clothes_id') and if it is, would that be a bad pratice? -
Display the dynamic table in a Django template
When I run this only code in separate python file, it will run perfectly. But using Django template the option chain does not print. Following error has been occurred: AttributeError at /nifty 'Response' object has no attribute 'META' my views code is ....... url = 'https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36 Edg/103.0.1264.37','accept-encoding': 'gzip, deflate, br','accept-language': 'en-GB,en;q=0.9,en-US;q=0.8'} session = requests.Session() request = session.get(url,headers=headers) cookies = dict(request.cookies) response = session.get(url,headers=headers,cookies=cookies).json() rawdata = pd.DataFrame(response) rawop = pd.DataFrame(rawdata['filtered']['data']).fillna(0) data = [] for i in range(0,len(rawop)): calloi = callcoi = cltp = putoi = putcoi = pltp = callvol = putvol = callpChange = putpChange = callIV = putIV = 0 stp = rawop['strikePrice'][i] if(rawop['CE'][i]==0): calloi = callcoi = 0 else: calloi = rawop['CE'][i]['openInterest'] callcoi = rawop['CE'][i]['changeinOpenInterest'] cltp = rawop['CE'][i]['lastPrice'] callvol = rawop['CE'][i]['totalTradedVolume'] callpChange = rawop['CE'][i]['pChange'] callIV = rawop['CE'][i]['impliedVolatility'] if(rawop['PE'][i] == 0): putoi = putcoi = 0 else: putoi = rawop['PE'][i]['openInterest'] putcoi = rawop['PE'][i]['changeinOpenInterest'] pltp = rawop['PE'][i]['lastPrice'] putvol = rawop['PE'][i]['totalTradedVolume'] putpChange = rawop['PE'][i]['pChange'] putIV= rawop['PE'][i]['impliedVolatility'] opdata = { 'CALL IV': callIV, 'CALL CHNG OI': callcoi,'CALL OI': calloi, 'CALL VOLUME': callvol,'LTP CHANGEC': callpChange, 'CALL LTP': cltp, 'STRIKE PRICE': stp, 'PUT LTP': pltp, 'LTP CHANGEP': putpChange, 'PUT … -
Invalid Tag static expected endblock
I am new django. I'm practicing it after finishing youtube videos. I'm facing the following error django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 42: 'static', expected 'endblock'. Did you forget to register or load this tag? The problem that it tells me that it can't find the endblock tag but I've put it at the end of the code. I don't know what causes this problem or how to solve it I need help please my html {% extends "Books/base.html" %} {% block content %} <div class="page" id="page"> <div class="main"> <div class="main-content"> {% for book in books %} <div class="container"> <div class="img"> <img src="{{ book.image.url }}" width="250px" height="300px" /> </div> <div class="title"> <a href="{% url 'details' book.id %}" target="_blank"> {{ book.title }} </a> </div> <p class="description">{{ book.mini_description }}</p> <p class="category"> {% for categ in book.category.all %} {% if categ == book.category.all.last %} {{ categ }} {% else %} {{categ}}- {% endif %} {% endfor %} </p> <h2 class="price">{{ book.price }} EGP.</h2> <h3 class="rate">{{ book.rate }}</h3> <a href="{% url 'buy' %}" target="_blank" ><button class="buy_now nav buy_now_position">Buy Now</button></a > </div> {% endfor %} </div> </div> <div class="nav-bar"> <header class="nav"> <a class="nav logo"> <img src="{% static 'images/Main Logo.png' %}" class="logo" alt="logo" /> </a> <a … -
Accessing extracted data from csv in django to create new class
Hi I’m working on a Django project where I’m iterating through a CSV file to extract data and then use that data to create an object (product). The products.models.py is structured as follows: from django.db import models class Product(models.Model): name = models.CharField(max_length=120) image = models.ImageField(upload_to='products', default='no_picture.png') price = models.FloatField(help_text='in US dollars $') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.name}-{self.created.strftime('%d/%m/%Y')}" The CSV I’m iterating through has the following structure: POS,Transaction id,Product,Quantity,Customer,Date 1,E100,TV,1,Test Customer,9/19/2022 2,E100,Laptop,3,Test Customer,9/20/2022 3,E200,TV,1,Test Customer,9/21/2022 4,E300,Smartphone,2,Test Customer,9/22/2022 5,E300,Laptop,5,New Customer,9/23/2022 6,E300,TV,1,New Customer,9/23/2022 7,E400,TV,2,ABC,9/24/2022 8,E500,Smartwatch,4,ABC,9/25/2022 Opening the csv file once it's added and iterating through it I do like this: if request.method == 'POST': csv_file = request.FILES.get('file') obj = CSV.objects.create(file_name=csv_file) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) reader.__next__() for row in reader: print(row, type(row)) # list data = ";".join(row) print(data, type(data)) # creates a str data = data.split(';') # creates a list print(data, type(data)) print(data) So far so good. I then prepare the elements by having a look at the output from the terminal: ['1', 'E100', 'TV', '1', 'Test Customer', '9/19/2022'] <class 'list'> 1;E100;TV;1;Test Customer;9/19/2022 <class 'str'> ['1', 'E100', 'TV', '1', 'Test Customer', '9/19/2022'] <class 'list'> ['1', 'E100', 'TV', '1', 'Test Customer', '9/19/2022'] Preparing an object from … -
Facebook login permissions user_photos
There are 2 profiles in process of Login. One profile can see Photos perm request, another profile does not see it. What does it mean? How can I solve it? -
Can not login as superuser in DRF
Created superuser several times with this credentials. username: admin password: root Did it with terminal and with Djnago ORM. Same result. >>> from bank.models import User >>> User.objects.create_superuser(username="admin", password="root") >>> from django.contrib.auth import authenticate >>> u = authenticate(username="admin", password="root") >>> u >>> type(u) <class 'NoneType'> >>> admin = User.objects.get(username="admin") >>> admin <User: admin> >>> admin.is_active True >>> admin.is_staff True >>> admin.is_superuser True It's started since I started using python-jwt tokens, but it fails before code goes to token part. Same login function as normal user works as it supposed to be and gives working token. @api_view(['POST']) def login_view(request): username = request.data.get("username") password = request.data.get("password") user = User.objects.filter(username=username).first() if user is None: raise exceptions.AuthenticationFailed("Invalid Credentials") if not user.check_password(password): # code fails here after trying lo log in as superuser raise exceptions.AuthenticationFailed("Invalid Credentials") token = services.create_token(user_id=user.id) resp = response.Response() resp.set_cookie(key="jwt", value=token, httponly=True) resp.data = {"token": token} return resp -
ValueError: Field 'id' expected a number but got '10.48.38.28'
I tried to search with Rest Framework a specific parameter in the sqlite using django but i get the following error: return int(value) ValueError: invalid literal for int() with base 10: '10.48.38.28' The above exception was the direct cause of the following exception: Traceback (most recent call last):... ValueError: Field 'id' expected a number but got '10.48.38.28'. [27/Sep/2022 13:23:59] "GET /sipinterface/?ipHost=10.48.38.28/ HTTP/1.1" 500 155723 MODELS class sipInterface(models.Model): siRealmId=models.CharField(max_length=75) siIpAddress=models.CharField(max_length=75) siPort=models.IntegerField() siTransportProtocol=models.CharField(max_length=75,null=True) siAllowAnonymus=models.CharField(max_length=75,null=True) ipHost = models.ForeignKey(host, on_delete=models.CASCADE) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: #nombre sing y plural de musica verbose_name="sipInterface" verbose_name="sipInterface" def __str__(self): return f"{self.siRealmId},{self.siIpAddress},{self.siPort},{self.siTransportProtocol},{self.siAllowAnonymus},{self.ipHost}" The Serializers file is the next: SERIALIZERS: from rest_framework import serializers from .models import sipInterface class sipInterfaceSerializer(serializers.ModelSerializer): class Meta: model=sipInterface fields=['siRealmId','siIpAddress','siPort','siTransportProtocol','siAllowAnonymus','ipHost'] The file of the view is the next: VIEW class sipInterfaceList(generics.ListAPIView): serializer_class=sipInterfaceSerializer def get_queryset(self): queryset = sipInterface.objects.all() ipHost = str(re.sub(r'/.*',"",self.request.query_params.get('ipHost', None))) if ipHost is not None: queryset = sipInterface.objects.filter() queryset = queryset.filter(ipHost=ipHost) #<--- THE ERROR! else: queryset = [] return queryset class sipInterfaceDetail(generics.RetrieveAPIView): queryset=sipInterface.objects.all() serializer_class=sipInterfaceSerializer def get_queryset(self): queryset = sipInterface.objects.all() ipHost = str(re.sub(r'/.*',"",self.request.query_params.get('ipHost', None))) if ipHost is not None: queryset = sipInterface.objects.filter() queryset = queryset.filter(ipHost=ipHost) else: queryset = [] return queryset I mark the line with the error with #<--- THE ERROR! Thanks for your help -
How to get string with space character in input value html
I have a class 'client' with a Charfield called 'address', this field have a space, for example 'via marconi' <div class="form-group"> <label for="address">Indirizzo:</label> <input type="text" class="form-control" id="address" name="address" value={{client.address}} Required> </div> In this case, when i get the value with "client.address" it give me only 'via' without read over the space. I'm trying to find a way for read the entire string with also the end of the string over the space character -
Virtualenv django package unresolved
I'm new to django and find my django package always unresolved, but the project runs successfully, the interpreter setting is right, the pip list shows the django package, I clip some pics here, can someone tell me how to remove these warnings? Are there any pronlems in environment variables or version conflicts? Warnings: enter image description here Interpreter setting: enter image description here project structure setting: enter image description here run/debug configuration: enter image description here -
Why do we need to login user in signup_view an login_view function? Django
So I need a theoretical answer here, not practical, I've been following this tutorial on Django anf everything seems quite understandable, but I'm not sure about one thing, so here are the views for signup page and login page: def signup_view(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() #log the user in login(request, user) return redirect("articles:list") else: form = UserCreationForm() return render(request, 'account/signup.html', {"form": form}) def login_view(request): if request.method == "POST": form = AuthenticationForm(data = request.POST) if form.is_valid(): #log in the user user = form.get_user() login(request, user) return redirect('articles:list') else: form = AuthenticationForm() return render(request, "account/login.html", {"form":form}) So my question is, why do I need to write login(request, user) twice, isn't the signup function saving the user in database and log in function simply logging it in?