Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I fix this issue on my social app? [duplicate]
I deployed my django app on Heroku using sqlite as database, I migrated. And still haven't seen my old data content on the site, I even had to create a new superuser to login. Now I said let's forget about the old db and posted some new content to make the site look alive, posted a couple of pics but after some time they disappear, just a white thumbnail on the post. The users I created are still there, just the pics they look broken or something.. Anyway I could fix this or even better find a way to use the old existent database. I still see it on my heroku console but not on the site even though I migrated. Link of the site: https://network50web.herokuapp.com/ Settings: """ Django settings for project4 project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import django_heroku from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used … -
Pythonanywhere ModuleNotFoundError No module named mysite
Hi I've been continuing to get this error on Pythonanywhere trying to run a Django project. Error is with the WSGI file but not sure what I'm doing wrong. Here is my WSGI file currently: import os import sys ## assuming your django settings file is at '/home/cole3237/mysite/mysite/settings.py' ## and your manage.py is is at '/home/cole3237/mysite/manage.py' path = '/home/cole3237/wintergarden_django' if path not in sys.path: sys.path.append(path) # os.environ['DJANGO_SETTINGS_MODULE'] = 'wintergarden_django.settings' # ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() The name of the root folder is correct (which seemed to be the problem for anyone whose had a similar problem) so not sure what the issue could be? Thank you for any help -
How to display Json format on Django?
I am building an application with Django. I want to display only the field without the number and data type as shown in the picture. I use data from CSV. Maybe I think this needs to be converted into Json. But I don't understand. This is my code: views.py def get_rbook(request, bookid): df_book = pd.read_csv(book_path) book_details = df_book[df_book['book_id'] == bookid] context = { 'book': book_details, } return render(request, "resources/read.html", context) HTML <div class="container-fluid"> <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> <div class="row"> <div class="col-sm-2"> <div class="grid-item"> <div class="view-details" style="cursor:pointer"> <img id="product_image" class="lookInsideImg" src="{{ book.image_url }}"> </div> </div> </div> <div class="col-sm-10"> <div class="product-information"> <h4>{{ book.original_title }}</h4> <p style="margin: 0px">by <a style="font-weight:bold" href="#">{{ book.authors }}</a></p> <div class='rating'> </div> <article class="text-justify" style="margin-top:10px;"> {{ book.desc }} </article> </div> </div> </div> </div> </div> </div> </div> Thank you before! -
Django: how to include CSS once within an "included" template
With Django templates, once can either {% extend %} or {% include %} a template. I have a template that already extends another template, and then there are various optional bits of code in templates which get included to the extended template. Thing of these included files as "components" which get added to various templates. Now one of these inlcuded templates requires an external CSS file. Although one could add the included file to all the templates which include it, I think logically it makes more sense that code snippet injects its own dependencies automatically, or else soft dependencies in far away files tends to get broken. i.e. the included template should declate its needs for the CSS file. If I write a custom template tag to achieve this, as far as I understand, by the time its gets to this template tag in the included template, it can't go back to the document head and add a line to the rendering of the head to add a <style> tag. So how can one achieve this? One could add the style tag in the component, but then the style tag is duplicated everytime there's an instance of the component, which … -
Powershell - How to get output from Python script program that's being run in Powershell and write it in a log file?
I'm looking to write the output that appears on the Powershell console of my Python script to the log file. How am I able to read it and write it to my log file? My powershell script: $LogFileTime = Get-Date -Format "yyyyMMdd_HHmmss" $LogFile = "D:\Project\_LOG\START_WEBSERVER_"+$LogFileTime+".log" $CurrDatetime = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $CurrDatetime+" | START WEBSERVER" | Add-Content -Path $LogFile D:\Project\Venv\Scripts\python.exe D:\Project\PowerShellScripts\manage.py runserver 0.0.0.0:80 > $LogFile 2>&1 $CurrDatetime = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $CurrDatetime+" | STOP WEBSERVER" | Add-Content -Path $LogFile My Python script: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
Getting user`s UUID from django server
I have a django server with an admin panel. Different users make changes there and this is saved via auditlog in the database and displayed in the "history". But there are situations when a user enters under the account of another user and makes changes on his behalf. In order to identify from which device this or that change was made, it was a nice decision to also record data about the IP of the user from whom the change was made, and his unique device number. By overloading several methods in the "AuditlogMiddleware" class, I got the desired result via "uuid.UUID(int=uuid.getnode())". (Tested locally, because the prod server is heavily loaded and there is no way to do test committees) from __future__ import unicode_literals import threading import time from auditlog.middleware import AuditlogMiddleware threadlocal = threading.local() class ExtendedAuditlogMiddleware(AuditlogMiddleware): def process_request(self, request): threadlocal.auditlog = { 'signal_duid': (self.__class__, time.time()), 'remote_addr': request.META.get('REMOTE_ADDR'), } super(ExtendedAuditlogMiddleware, self).process_request(request) **#changes here import uuid threadlocal.auditlog['additional_data'] = str(uuid.UUID(int=uuid.getnode()))+" | "+request.META["USERNAME"]** # @staticmethod def set_actor(self, user, sender, instance, signal_duid, **kwargs): super(ExtendedAuditlogMiddleware, self).set_actor(user, sender, instance, signal_duid, **kwargs) **#changes here instance.additional_data = threadlocal.auditlog['additional_data']** But the problem is that I think I get the UUID not of the user, but of the server, because … -
UUIDs with django and mssql
I have a mssql schema with the django ORM / pymssql extension. I have some classes build via the inspectdb function. A lot of the Primarykeys in the tables are UUID fields / mssql uniqueidentifier, which the ORM inspected as CharFields with length 36. I am concerned now with possible duplicates for the primary keys since the tables are growing very fast. The tables have a default constraint for any new primary key on the database site. So basically I have two (different) sources of UUID generation (the database server and the application server) How is it possible to insert via the ORM from django performantly? Am I save with generating the UUIDs via pythons uuid module or do I have to ask the database everytime for a new UUID before creating a object with django? -
How to have a choice depending on the instance of a model in Django admin
I am stuck since quiet a few days now. I have a level 1 model, which is in 0 to Many relation with a level 2 model, which is in a 0 to Many relation with a level 3 model: class Level1(models.Model): title = models.CharField(max_length=30) # some fields class Level2(models.Model) title = models.CharField(max_length=30) # some Fields level1 = models.ForeignKey(Level1, on_delete=models.CASCADE) class Level3(models.Model) title = models.CharField(max_length=30) # some Fields level2 = models.ForeignKey(Level2, on_delete=models.CASCADE) choices = # I get stuck here # The field 'choices' must point to one level2 instance proposed through a kind of Choices form field, but maybe I am wrong. By pointing, I think it can be as well a relation or just storing the id of the Model instance. The choices must be limited. Here an example would be the simplier way to explain : Level 1 : objects : A, B Level 2 : objects : A1, A2, A3 : (Parent A); B1, B2 : (Parent B) Level 3 : object A10 : (parent A1) For A10 choices must be limited to A1, A2, A3. And that's it. Thank you in advance for your help. -
Get field from cursor select (mssql) in my template
I have this VIEW below: from django.shortcuts import render from django.db import connections def IndexView(request): con_totvs = connections['totvs'].cursor() with con_totvs as cursor: cursor.execute("SELECT A1_NOME, A1_CGC FROM SA1010 WHERE D_E_L_E_T_ <> '*' ORDER BY A1_NOME") select = cursor.fetchall() # bla bla bla context = {} cursor.close () con_totvs.close () return render(request, "home.html", context) Just like I use when creating models, in my template id like to do something like: {% for i in SELECT %} {{ i.A1_NOME }} {% endfor %} Is this possible? Ive been searching but i failed it -
Convert template html in django to pdf and download it
How I can create a button on my web page using Django to convert the page to PDF and download it ? -
Django Rest API Models Problem an unexpected keyword argument 'is_staff'
i have error ExtendedUser() got an unexpected keyword argument 'is_staff' This is my model.py class ExtendedUser(AbstractBaseUser): objects = UserManager() id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=100) last_name= models.CharField(max_length=100) username = models.CharField(max_length=100) email = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) password = models.CharField(max_length=50) def __str__(self): return str(self.first_name) and this is my serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = ExtendedUser fields = ['id','first_name','last_name','password','email'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = ExtendedUser.objects.create_user(validated_data['first_name'], validated_data['email'], validated_data['password']) return user What is problem , how to avoid this problem ? i do't want to use is_staff field -
How to compare the value of an input with an object field in django template?
I want to compare the value of an object field to the value of an input that i have set the value with jQuery on a click event. Here is the jQuery function: <script> $(document).ready(function() { $('.position').click( function(){ var id=$(this).attr('id'); alert(id) $('.info-tooltip').toggleClass("hidden"); $('.header').addClass("popup"); $('.section').addClass("popup"); $('#map-value').val(id); }, ) $('.remove-link').click( function(){ $('.info-tooltip').addClass("hidden"); $('.header').removeClass("popup"); $('.section').removeClass("popup"); }, ) }); </script> I want to access the value of the input with the id="map-value" with the id of the object field that I am accessing it with an for cycle like this <form> <input type="text" value="1" id="map-value" name="map-value"> </form> {% for p in points %} {% if p.id == form.input.value %} //i will show sth here {% endif %} {% endfor %} -
Why my own css file is not loading after installation of django-cripsy-form?
I created an website using django (HTML, CSS etc). Everyithing was fine until I wanted to add a login/register form. I used django, templates. But when I installed django-crispy-forms my css was not loading anymore. Only the register form looks good now but the other stuff like logo, menu, etc are ignoring my css. That's how I loaded my css and it worked until django-crispy-forms {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> Only below form looks good due to the django-crispy-forms package. {% load crispy_forms_tags %} <div class="container pt-5"> <form method="POST" class="form-group"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Register </button> </form> </div> -
Dockerfile. Can a CMD read an Argument?
I am new to docke but I am trying to do something like this in the dockerfile ARG ENV CMD echo $ENV CMD [ "manage.py","runserver", "0.0.0.0:8000", "--settings={ENV}" ] And I want to pass the ENV argument from the docker build as build-args. I want to run django based on the environment(staging/production/etc) but looks like CMD is not reading the argument. -
Can I Reorder a LIst Based On User Provided Values Using Only HTMX?
I have HTMX working. The code below is fully functional. The one piece I'd like to incorporate, I can't figure out how to do it. The user is able to provide a number rank...but when they click save, the view returns with the item at the top. Only after they click reload does the list sort itself based on how I defined the attributes with the model. Here's my HTML... <h1 class="title62">Tasks</h1> <button class="button36" hx-get="{% url 'MyTasks:create_task_form' %}" hx-target="#taskforms">Add Task</button> <div id="taskforms"></div> <div id="tblData"> {% if tasks %} {% for task in tasks %} {% include "partials/task_detail.html" %} {% endfor %} </div> {% endif %} <div hx-target="this" hx-swap="outerHTML" hx-headers='{"X-CSRFToken":"{{ csrf_token }}"}' class="" > <form method="POST"> {% csrf_token %} <div class="table22"> <table class="table23"> <thead> <tr> <th class="title67">Number</th> <th class="title67">Task</th> </tr> </thead> <tbody> <button class="button35" hx-post="."> Save </button> <button type="button" class="button33"> Delete </button> <tr> <td class="title73">{{ form.number }}</td> <td class="title73">{{ form.task }}</td> </tr> </tbody> </table> </div> </form> </div> <script> document.body.addEventListener('htmx:configRequest', (event) => { event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}'; }) </script> <div hx-target="this" class=""> <div class="table22"> <table class="table23"> <thead> <tr> <th class="title67">Number</th> <th class="title67">Task</th> </tr> </thead> <tbody> <button class="button35" hx-get="{% url 'MyTasks:update_task' task.id %}" hx-swap="outerHTML"> Update </button> <button class="button34" hx-confirm="Are you sure you … -
pytest how to run tests / django
I'm trying to use pytest for the 1st time in my new created app but i'm facing problems with running it. I still receive 'no tests ran in...' message. My project name is PROJECT, then is my app called diet_app and file tests.py inside the app folder. How to run tests? I tried with: pytest pytest tests pytest diet_app To be more precise - to install pytest i used: pip install pytest pip install pytest-django Maybe I'm missing something obvious but as i said - this is my 1st time using it. I'm working in Pycharm -
comparing value from inputfield with django model data
I have already made an app that allows me to study. It contains multiple test with multiple question with one correct answer each. class Test(models.Model): name = models.CharField(max_length=200) #questions = models.ManyToManyField(Question) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True) date_posted = models.DateTimeField(auto_now_add = True) def get_questions(self): return self.question_set.all() def __str__(self): return self.name class Question(models.Model): text = models.CharField(max_length=200, null=True) test = models.ForeignKey(Test, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add = True) def get_answer(self): return self.answer_set.all() def __str__(self): return self.text class Answer(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='parent') def __str__(self): return self.text I made JS funtion that compare user answer from input field with correct answer put in html function PointsCounter(){ var points = 0; const elements = document.querySelectorAll('.question-container'); Array.from(elements).forEach((element, index) => { var CorrectAnswer = (((element.querySelector('div form p')).innerHTML).toLowerCase()).trim(); var UserAnswer = (((element.querySelector('div form p input')).value).toLowerCase()).trim(); if(UserAnswer == CorrectAnswer){ points++; }}) document.getElementById("points").innerHTML=points; } Instead of putting correct answer in my html code: <p id="ans" hidden>{{ question.parent.all.last }}</p> I'd like to compare user answer with answer from database, but I do not know how to achieve it. I mean, i'd like to pass correct answer to js function to disallow user to check answer by inspecting html code of page. How can I make it … -
How to update an object with function base views?
Here i'm updating my object with PUT method. When I git the api. It only update those fields which are blank. Those fields which has some text or data already are not updating.. this is data i put : { "email": "main@gmail.com", "first_name": "yes same", //this field has already value and this is not updating "middle_name": null, "last_name": "in", "age": null, "gender": null, "bio": null, "city": null, "street_address": null, "state": "punjab", // this field was null and i gave it some value and it updated "country": "pakistan" // this field was null and i gave it some value and it updated } Object in response : "data": { "id": 1, "email": "main@gmail.com", "first_name": "ma", "middle_name": null, "last_name": "in", "age": null, "gender": null, "bio": null, "city": null, "street_address": null, "state": "punjab", "country": "pakistan" } My code : @api_view(['GET','PUT']) @permission_classes([IsAuthenticated]) @csrf_exempt def update_profile(request,id): profile = UserProfile.objects.if_obj_exists(id) print(profile) if request.method=="GET": serializer = UserProfileSerializer(profile, many=False) return Response({"status":"success","message": "Ok", "data": serializer.data},status=status.HTTP_200_OK) elif request.method=="PUT": serializer = UserProfileSerializer(instance=profile,data=request.data) print(serializer.is_valid()) if serializer.is_valid(): serializer.save() return Response({"data": serializer.data},status=200) return Response({"status":"fail","message": "something went wrong"},status=400) -
How can I check if two objects from differente models equal each other in Django?
I have 2 models, one for Students and another for Faculty. I need to print all Students from one specific Faculty. Model for Faculty class Fakultet (models.Model): fakultet_naziv=models.CharField(max_length=30) fakultet_adresa=models.CharField(max_length=30) fakultet_kontakt_broj=models.CharField(max_length=20) fakultet_email_referade=models.EmailField(default='') fakultet_website=models.URLField() def __str__(self): return self.fakultet_naziv Model for Students class Student (models.Model): student_ime=models.CharField(max_length=30) student_prezime=models.CharField(max_length=30) student_jmbag=models.CharField(max_length=10, primary_key=True) student_adresa=models.CharField(max_length=30, default='') student_email=models.EmailField(default='') student_fakultet=models.ForeignKey(Fakultet, on_delete=models.CASCADE, default='') student_cijepljen=models.BooleanField(default=True) student_cjepivo=models.ForeignKey(Cjepivo, on_delete=models.CASCADE, default='') student_datum_cijepljenja=models.DateTimeField(default=timezone.now) student_datum_isteka_potvrde=models.DateTimeField(default=timezone.now) student_prebolio_covid=models.BooleanField(default=False) def __str__(self): return self.student_jmbag First i tried this method and it didn't work. It didn't show any students at all. def fakultetstudent(request): fakultet = Fakultet.objects.values_list('fakultet_naziv', flat=True) fakultetstudent = Student.objects.filter(student_fakultet__in=fakultet).exists() context = {'fakultetstudent' : fakultetstudent} return render(request, 'main/fakultetstudent.html', context = context) After that i tried this and def fakultetstudent(request): fakultet = Fakultet.objects.values_list('fakultet_naziv') student = Student.objects.values_list('student_fakultet') context = {'faklutet' : fakultet, 'student' : student} if fakultet == student: return render(request, 'main/fakultetstudent.html', context = context) and error is: The view main.views.fakultetstudent didn't return an HttpResponse object. It returned None instead. Pleas help me with this problem. -
Create a JavaScript chart in HTML with a date selector
I used gspread and pandas to convert my google sheet into a list of dictionaries. My google sheet is shown as the following list: (It's a very long list, so I only list a few lines) mylist= [{'Date': '2021-10-02', 'ID': 11773, 'Receiver': Mike}, {'Date': '2021-10-02', 'ID': 15673, 'Receiver': Jane}, {'Date': '2021-10-03', 'ID': 11773, 'Receiver': Mike}, ... {'Date': '2021-12-25', 'ID': 34653, 'Receiver': Jack}] It's a Django project, so my data is defined in views.py: I count the number of records with Mike, Jane and Jack. tsheet2022 = client.open('Return Record 2022') tinstance2022 = tsheet2022.get_worksheet(0) mylist = tinstance2022.get_all_records() mike=len(tuple(d for d in t2022 if d['Receiver'] == 'Mike')) jane=len(tuple(d for d in t2022 if d['Receiver'] == 'Jane')) jack=len(tuple(d for d in t2022 if d['Receiver'] == 'Jack')) count = [mike, jane, jack] I have already drawn a pie chart based on my total counted data in my chart.HTML file : <!-- pie Chart --> <div class="col-xl-4 col-lg-4"> <div class="card shadow mb-4"> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <h6 class="m-0 font-weight-bold">Team Chart</h6> </div> <!-- Card Body --> <div class="card-body"> <div class="chart-area"> <canvas id="myPieChart"></canvas> <script> var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["Mike", "Jane", "Jack"], datasets: [{ data: … -
Cannot run django function
I am following a tutorial on youtube on learning Django.The person i am following is using a macbook and i am on windows.The person run this command in his terminal trying to start a new project and he entered this code django-admin startproject storefront and he was successfull.But when i tried it for windows it gave an error. I googled the error and got a solution python -m django startproject storefront Then the man wanted to run the server using this code manage.py runserver and he was successfull but when i tied on windows it gave this error mange.py' is not recognized as an internal or external command, operable program or batch file. -
App loaded in Django admin, but doesn't showing up
I am trying to add my app to django admin panel. I have 3 apps: users orders advertisements All this applications loaded in settings.INSTALLED_APPS correctly, but django-admin showing up only two apps: users and orders. The most interesting in this situation is that in source code of html file for django-admin panel all apps are loaded, but app advertisements doesn't showing up. As you can see below, code for advertisements app is loaded in html file. When I try to go on links for this app in a tags, i see only white screen on opened page, but source code for page is loaded too. Thanks a lot for any help. <div id="content-main"> <div class="app-advertisements module"> <table> <caption> <a href="/admin/advertisements/" class="section" title="Models in the Advertisements application">Advertisements</a> </caption> <tr class="model-advertisingspacecategory"> <th scope="row"><a href="/admin/advertisements/advertisingspacecategory/">Advertising space categorys</a></th> <td><a href="/admin/advertisements/advertisingspacecategory/add/" class="addlink">Add</a></td> <td><a href="/admin/advertisements/advertisingspacecategory/" class="changelink">Change</a></td> </tr> <tr class="model-advertisingspace"> <th scope="row"><a href="/admin/advertisements/advertisingspace/">Advertising spaces</a></th> <td><a href="/admin/advertisements/advertisingspace/add/" class="addlink">Add</a></td> <td><a href="/admin/advertisements/advertisingspace/" class="changelink">Change</a></td> </tr> </table> </div> <div class="app-auth module"> <table> <caption> <a href="/admin/auth/" class="section" title="Models in the Authentication and Authorization application">Authentication and Authorization</a> </caption> <tr class="model-group"> <th scope="row"><a href="/admin/auth/group/">Groups</a></th> <td><a href="/admin/auth/group/add/" class="addlink">Add</a></td> <td><a href="/admin/auth/group/" class="changelink">Change</a></td> </tr> </table> </div> <div class="app-orders module"> <table> <caption> <a href="/admin/orders/" class="section" title="Models in the Orders … -
Howto Python Request in Django
I am very new to Django, I am trying to request informations from another side to display them on my own. My site works and outside of Django I can request. I have no idea how to request and display the informations in Django neither where to do this in the project. Please help. models.py: from django.db import models class Form(models.Model): ipName = models.CharField(max_length=100) ipAddress = models.CharField(max_length=100) ipKey = models.CharField(max_length=100) ipSecret = models.CharField(max_length=100) ipMask = models.CharField(max_length=100) ipWahrheit = models.BooleanField(default=True) def __str__(self): return self.ipName views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Form import requests def home(request): context = { 'ox': Form.objects.all() } return render(request, 'Ips/home.html', context) home.html: {% extends "Ips/Ips.html" %} {% block content %} {% for ip in ox %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ ip.ipName }}</a> <small class="text-muted">{{ ip.ipAddress }}</small> </div> <p class="article-content">{{ ip.ipName }}</p> </div> </article> {% endfor %} {% endblock content%} With the Informations i get from Form i want to make an request to that Ip address and get back a jason. -
Django contact form sending email back to my own email address
views.py def contact(request): if request.method == "POST": username = request.POST['username'] phone = request.POST['phone'] customer_email = request.POST['customer_email'] subject = request.POST['subject'] message = request.POST['message'] #send Email send_mail(subject, message, customer_email, ['myemail@gmail.com']) return render(request, 'contact.html', {'username': username }) else: return render(request, 'contact.html', {}) This is my html <form method="post" action="{% url 'contact' %}" id="contact-form"> {% csrf_token %} <div class="row clearfix"> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="text" name="username" placeholder="Name" required=""> </div> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="text" name="phone" placeholder="Phone" required=""> </div> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="email" name="customer_email" placeholder="Email" required=""> </div> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="text" name="subject" placeholder="Subject" required=""> </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group"> <textarea name="message" placeholder="Message"></textarea> </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group"> <button class="theme-btn btn-style-one" type="submit" name="submit-form">Submit Now</button> </div> </div> </form> This is the form I have that should send an email to customer_email, but instead I am getting the email back to me. That is, sender and recipient are both same. What is the issue here. Also is it possible to add the customer's email and phone number in the email message itself. Kindly help. -
'ASGIRequest' object has no attribute 'Get'
Got an error when trying django (4.0.2), the error thrown was: 'AsgiRequest' object has no attribute 'Get' Running with channels 3.0.4, Django 4.0.2, python 3.8 Running via python3 manage.py runserver from django.shortcuts import render,redirect from django.contrib import messages from .models import * # Create your views here. def home(request): if request.method == 'post': username=request.POST.get('username') option=request.POST.get('option') room_code=request.POST.get('room_code') if option=='1': game=Game.objects.filter(room_code=room_code).first() if game is None: messages.success(request, 'Room code not found') return redirect('/') if game.is_over: messages.success(request, 'Game is over') return redirect('/') game.game_opponent=username game.save() else: game=Game(game_creater=username,room_code=room_code) game.save() return redirect('/game/'+room_code+'?username=' + username) return render(request, 'home.html') def game(request, room_code): username=request.Get.get('username') context={'room_code': room_code , 'username' : username} return render(request, 'play.html', context)