Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to segment WebM audio data
Consider a basic web application which livestreams audio from one client to the server and then back down to many other clients. So far so good, I setup a website that just does that using just JavaScript and Django (Python). However, there is a bug in my approach. If someone loads the website in the middle of a livestream the audio does not play. After lots of investigation, this is due to the lack of an initialization segment and not properly segmenting the audio data. A little more context here: Unable jump into stream from media recorder using media source with socket.io So before I heed the advice from StackOverflow and rip this WebM audio file apart byte by byte - has someone else done the hard work for me already? In Python, what is the easiest way for me to extract the initialization segment and each successive audio cluster from an WebM audio file? To be specific, the file is being created from the front-end using this mimeType: new MediaRecorder(mediaStream, {'mimeType': 'audio/webm; codecs="opus"',}); -
activating virtual environment on windows using powershell
Im following this tutorial: https://www.codingforentrepreneurs.com/blog/install-python-django-on-windows/ on step 7, I tried running pipenv shell in the same directory called cfehome, and also in a different directory, but it doesnt say the (cfehome) before the path, so i thought it hadnt been activated, but when I run the command again, it says environment already activated. Also, the tutorial states when i run pip freeze, i should get no output. but i do get an output with the names of different libraries. I followed all other steps and they gave the desired output so I dont know why this step is not? -
Django querysets filter in each object related in a many to many field?
i'm working in a view to filter some data and sent it back. I wanna filter by this FKs, alredy working on the FK user to FK account atribute of my Book model, now the problem is i have a ManyToMany field toand need to do the same filter for each of that authors. The what: if 'want_book' in requestData: if program_id != 'Programa educativo' and academy_id != 'Cuerpo academico': book_list = (Book.objects.filter( user__account__program=program_id).filter( user__account__academy=academy_id) |Book.objects.filter( authors__*foreachauthor*__program=program_id)).distinct() My models: class Book(models.Model): project = models.ForeignKey(Project, on_delete=models.PROTECT, verbose_name = "Proyecto") user = models.ForeignKey(UserSap, on_delete=models.PROTECT,verbose_name = "Autor principal") authors = models.ManyToManyField(Account,blank=True,verbose_name = "Otros Autores") ... class UserSap(AbstractBaseUser, PermissionsMixin): email = models.EmailField( max_length=100, verbose_name="Correo UABC", unique=True) account = models.OneToOneField( Account, on_delete=models.PROTECT, blank=True, null=True) class Academy(models.Model): name = models.CharField( max_length=100, verbose_name="Cuerpo académico", blank=True class Program(models.Model): name = models.CharField( max_length=100, verbose_name="Nombre del programa", blank=True) class Account(models.Model): program = models.ForeignKey( Program, on_delete=models.PROTECT, verbose_name="Programa educativo", blank=True, null=True) academy = models.ForeignKey( Academy, on_delete=models.PROTECT, verbose_name="Cuerpo académico", blank=True, null=True) any idea? -
how to make a JSON for this highchart - django app
I am working on django project I want to do a highchart dependency wheel but I don't know why the chart not showing , you will see my code below , in my dependencywheel.html I did already {%load static%} in the top <script> Highcharts.chart('container', { title: { text: 'Highcharts Dependency Wheel' }, accessibility: { point: { valueDescriptionFormat: '{index}. From {point.exped} to {point.destin}: {point.count}.' } }, series: [{ keys: ['exped', 'destin', 'count'], data: '{%url "data"%}', type: 'dependencywheel', name: 'Dependency wheel series', dataLabels: { color: '#333', textPath: { enabled: true, attributes: { dy: 5 } }, distance: 10 }, size: '95%' }] }); </script> this is my class in models.py class mail_item_countries_depend(models.Model): exped = models.CharField(max_length=100) destin = models.CharField(max_length=100) count = models.IntegerField(default=0) that's my views.py @login_required def depend(request): return render(request,'dependWheel.html',{}) def jsonDepend(request): dataset = mail_item_countries_depend.objects.all().values('exped','destin','count') data = list(dataset) return JsonResponse(data, safe=False) so the data looks like this : [{"exped": "MA", "destin": "AL", "count": 2}, {"exped": "MA", "destin": "BS", "count": 1}, {"exped": "AR", "destin": "DZ", "count": 2}, I already wrote a static data like this below to see if the dependency wheel gonna work and it worked data: [ ['Brazil', 'Portugal', 5], ['Brazil', 'France', 1], ['Brazil', 'Spain', 1], ['Brazil', 'England', 1], ['Canada', 'Portugal', 1], … -
Django, and React inside Docker inside a single Digital Ocean Droplet: 400 Bad Request for Django, React works fine
I have Django and React inside the same Docker container using docker-compose.yml and running this container inside a Digital Ocean Droplet running Ubuntu. When I navigate to http://my_ip_address:3000 which is the React app, it works just fine, but when I navigate to http://my_ip_address:8000 which is the Django app, I get a 400 Bad Request error from the server. project/back-end/Dockerfile FROM python:3.7 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /nerdrich COPY Pipfile Pipfile.lock /nerdrich/ RUN pip install pipenv && pipenv install --system COPY . /nerdrich/ EXPOSE 8000 project/front-end/Dockerfile # official node.js runtime for Docker FROM node:12 # Create and set the directory for this container WORKDIR /app/ # Install Application dependencies COPY package.json yarn.lock /app/ RUN yarn install --no-optional # Copy over the rest of the project COPY . /app/ # Set the default port for the container EXPOSE 3000 CMD yarn start project/docker-compose.yml version: "3" services: web: build: ./back-end command: python /nerdrich/manage.py runserver volumes: - ./back-end:/nerdrich ports: - "8000:8000" stdin_open: true tty: true client: build: ./front-end volumes: - ./front-end:/app - /app/node_modules ports: - '3000:3000' stdin_open: true environment: - NODE_ENV=development depends_on: - "web" command: yarn start project/back-end/nerdrich/.env ALLOWED_HOSTS=['165.227.82.162'] I can provide any additional information if needed. -
Related fields on model?
There is a model ElectoralTable class ElectoralTable(models.Model): name = models.CharField(max_length=250) country_owner = models.ForeignKey(Country, on_delete=models.CASCADE) city_owner = models.ForeignKey(City, on_delete=models.CASCADE) address = models.CharField(max_length=400) latitude = models.CharField(max_length=250, blank=True) longitude = models.CharField(max_length=250, blank=True) How can I to select a city related to a country. Rigth now I receive every city on Model City but I want only to receive the cities related wiht country owner -
Getting Jquery error while integrating ADMINLTE template in django
I am getting error while i was integrating ADMINLTE3 in django . i was developing webapp so for admin dashboard I was using it. But I did everything right still I am getting lots of error in the console about the jquery. can anyone help me on this error solving please. My console screen shot: browser consle screenshot -
Validating a choice field with ModelSerializer with Django
I have a model BaseUser which inherits from AbstractUser and has two additional fields: complex_list and active_complex. complex_list is a ManyToManyField connected to the BaseComplex model through an enrollment table. I want the default value for active_complex to be null which can be taken care of at the model initiation. I also need the user to be able to choose the active_complex only from the values within the complex_list. For that, I tried to use a customized ModelSerializer: from rest_framework import serializers from .models import BaseUser class ActiveComplexSerializer(serializers.ModelSerializer): this_user = serializers.SerializerMethodField('get_this_user') choice =[] qs = BaseUser.objects.get(username = this_user) for cmplx in qs.complex_list: choice.append((cmplx.id, cmplx.name)) active_complex = serializers.ChoiceField(choices = choice) class Meta: model = BaseUser fields = ('active_complex') def get_this_user(self, request): return request.user I know I'm doing something wrong because I get a query not found ERROR. I would appreciate it if you could correct this or suggest a better approach to achieving the same goal. -
Materialize autocomplete not updating v-model of Vue app
So I'm using Django, Vue, and Materialize. Just using Vue to have some smoother functionality. I have a text input that has a v-model on it. I'm also using Materialize's autocomplete component on it. When I select an option from the autocomplete, it does not update the data in vue that I have attached to the "v-model". The v-model just stays with the data I have typed in so far. How do I get around/fix that? How do I update the vue data on materialize's autocomplete? https://materializecss.com/autocomplete.html -
Django password reset/change view
I want to implement password reset/change feature in my app i just googled it & saw everyone using Django default Authentication Views. Is this the best way to do this? I'm new to django so i don't know much about this so suggest me the best way to do this. currently i implemented this path('password_change/done/', auth_view.PasswordChangeDoneView.as_view( template_name='registration/password_change_done.html'), name='password_change_done'), path('password_change/', auth_view.PasswordChangeView.as_view( template_name='registration/password_change.html'), name='password_change'), path('password_reset/done', auth_view.PasswordResetDoneView.as_view( template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_view.PasswordResetConfirmView.as_view( template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'), path('password_reset/', auth_view.PasswordResetView.as_view( template_name='registration/password_reset_form.html'), name='password_reset'), path('reset/done/', auth_view.PasswordResetCompleteView.as_view( template_name='registration/password_reset_complete.html'), name='password_reset_complete') -
Django auto repost data a week, month or a year depending on it's frequency of recurrence
In my django project I am trying to repost a record based on its frequency of recurrence which could be daily, weekly, monthly etc. Let's say a record is posted today and it's frequency of recurrence is weekly, I want the record to keep reappearing on a weekly basis on the 'day' and 'time' as the previous week when it was created and so on, that is, an old record will be new and top of other records which will now be older than it based on frequency of recurrence. models.py class Menu(models.Model): none = 0 Daily = 1 Weekly = 7 Monthly = 30 Quarterly = 90 SemiAnual = 180 Yearly = 365 Frequency_Of_Reocurrence = ( (none, "None"), (Daily, "Daily"), (Weekly, "Weekly"), (Monthly, "Monthly"), (Quarterly, "After 3 Months"), (SemiAnual, "After 6 Months"), (Yearly, "After 12 Months") ) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) name = models.CharField(verbose_name="food name", null=False, blank=False, max_length=100) description = models.TextField(verbose_name="Food Description", max_length=350, null=False, blank=False) image = models.ImageField(upload_to=user_directory_path, default='veggies.jpg') isrecurring = models.BooleanField(default=False) frequencyofreocurrence = models.IntegerField(choices=Frequency_Of_Recurrence) datetimecreated = models.DateTimeField(verbose_name='date-time-created', auto_now_add=True) How exactly can I achieve what I'm trying to do in my views. Thanks in advance. -
How to check if one field matches another in Django Form
I'm trying to have my form check if the email field matches the verify_email field in my Django form but it is not working. My forms.py file: class SignupForm(ModelForm): class Meta: model = FormSubmission fields ='__all__' widgets = {'botcatcher': forms.HiddenInput()} def clean(self): cleaned_data = super().clean() email = self.cleaned_data.get('email') vmail = self.cleaned_data.get('verify_email') if email != vmail: raise forms.ValidationError(_("Emails must match"), code="invalid") return cleaned_data My model.py file: class FormSubmission(models.Model): first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30) email = models.EmailField(unique= False) verify_email = models.EmailField(unique = False) text = models.CharField(max_length=250) botcatcher = models.CharField(max_length= 1, blank=True, validators=[validators.MaxLengthValidator(0)]) def __str__(self): return "%s %s"% (self.first_name, self.last_name) -
ReportLab get_FOO_display() Not Working On A List
Ive created a form which users fill out, then it uses reportlab to create a pdf of their answers. It works well except for a charfield (preferred_topics) which contains a list. Data is saved like this: ['ANI', 'EDU', 'ENV'] I think that might be a problem as id exect it to save the data like this: [['ANI'], ['EDU'], ['ENV']] However it works fine on the website. So to print human readable data to the pdf im using get_FOO_display(), but this doesnt work for preferred_topics. If i call (user.personalinformation.get_preferred_topics_display() i get: AttributeError at /enrolment/final_question/ 'PersonalInformation' object has no attribute 'get_preferred_topics_display' Here is my other relevant code: utils.py # generate pdf def generate_pdf(request): # get user user = request.user # data that will be printed to the pdf page_contents = [ ['Personal Information'], ['Name:', '%s %s' %(user.personalinformation.first_name, user.personalinformation.surname)], ['E-mail:', '%s' %(user.email)], ['Gender:', '%s' %(user.personalinformation.get_gender_display())], # this field is causing grief ['Preferred Topics:', '%s' %(user.personalinformation.preferred_topics)] ] forms.py TOPICS = ( ('ANI', 'Animals'), ('ART', 'Art'), ('COM', 'Communication'), ('CRI', 'Crime'), ) preferred_topics = forms.MultipleChoiceField(choices=TOPICS, required=False, widget=forms.CheckboxSelectMultiple()) Im expecting to be told that the data is being saved wrongly in my db, but dont know how to change it, and wanted confirmation before i started changing … -
django template - how to show different html based on for loop
Hello I'm trying to display a list in an html template which will display the information in a different configuration depending on the index of the list element. however, I'm getting all the information displayed with the html defined between the first condition and I can't figure out why is it not working. Excuse me for my bad programming I'm new at this. Can anyone help??? THANKS! this is my code so far: {% for service in service_list %} <section class="section {{service.bg}}" id={{service.tag}}> <div class="container"> <div class="row align-items-center"> {% if loop.index is odd %} <div class="col-lg-8"> <h2 class="text-white mb-3">{{service}}</h2> <p class="text-white lead">{{service.abstract}}</p> </div> <div class="col-lg-4 text-lg-right"> <a href="{% url 'main:spec_service' %}" class="btn btn-outline-white px-4 py-3">{{service.btn_text}}</a> </div> {% else %} <div class="col-lg-4 text-lg-left"> <a href="{% url 'main:spec_service' %}" class="btn btn-outline-white px-4 py-3">{{service.btn_text}}</a> </div> <div class="col-lg-8"> <h2 class="text-white mb-3 text-lg-right">{{service}}</h2> <p class="text-white lead">{{service.abstract}}</p> </div> {% endif %} </div> </div> </section> {% endfor %} -
Changing in the Quantity of variants reflecting in the wrong item in Order Summary
I have a problem with the variations and the quantity related to it in the order summary page. It was working perfectly and all of a sudden (this is an example to simplify): when I add to the cart 2 items: Item X with a size small Item X with a size medium When I change the quantity of item X size medium, this change is reflecting in item X size small which was chosen first. In the order summary, there are a plus and minus in the template to change the quantity. I have identified the problem but I can't figure out why it is occurring Here is the template: <h2> Order Summary</h2> <tbody> {% for order_item in object.items.all %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ order_item.item.title }}</td> <td>{{ order_item.item.price }}</td> <td> <a href="{% url 'core:remove-single-item-from-cart' order_item.item.slug %}"><i class="fas fa-minus mr-2"></a></i> {{ order_item.quantity }} <a href="{% url 'core:add-to-cart' order_item.item.slug %}"><i class="fas fa-plus ml-2"></a></i> </td> <td> {% if order_item.variation.all %} {% for variation in order_item.variation.all %} {{ variation.title|capfirst }} {% endfor %} {% endif %} </td> Here is the views.py class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, … -
In VS Code is there any shortcut to make {% %} for Django?
Is there any keyboard shortcut or extension that contains a shortcut where {% %} is automatically written out, and preferably the cursor is placed inside? Just starting with learning Django and it seems like you'll be using this enough that a shortcut would be useful. -
Django form is valid return that is NOT valid and error unknown
can anybody help me understand why the form is not validating? I have the following error: > I don't get any error message unless I print the form.is_valid The code is similar to what I normally use so it is strange that is not working this time.. I've looked the code over and over but can't find the issue. Let me know if there is more code I should show Thank you for any help you could provide. Views.py @login_required(login_url="sign-in") def restaurant_add_meal(request): form = MealForm() if request.method == "POST": form = MealForm(request.POST, request.FILES) if form.is_valid(): new_meal = form.save(commit=False) new_meal.restaurant = request.user.restaurant new_meal.save() messages.success(request, "It's saved!") return redirect(restaurant_add_meal) return render(request, "restaurant/dashboard/add_meal.html", {"form": form},)</code> And this is forms.py class MealForm(forms.ModelForm): meal_name = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}), max_length=500, required=True, ) short_description = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}), max_length=500, required=True, ) image = forms.ImageField( widget=forms.FileInput(attrs={"class": "form-control dropify"}), required=True, ) price = forms.IntegerField( widget=forms.TextInput( attrs={"class": "form-control price", "placeholder": "0.00"} ), required=True, ) category = forms.CharField( widget=forms.TextInput( attrs={"placeholder": "Ex. starters", "class": "form-control"} ), max_length=500, required=False, ) class Meta: model = Meal exclude = ("restaurant",) -
Linking Urls in django
I recently started learning as a way of setting foot in python programming. I've been facing problems with URLs since I'm a beginner. So I've been doing this signature verification web app. I'm not facing major problems except when it comes to URL patterns. When I enter the localhost address and the port and execute the program, it displays this error displayed here. I've gone to the URL files on Django and I see no errors on the code that I've written and also on the main folders URL. Can someone help me find the problem or what I'm doing wrong by checking the images and telling me? Thank you to all the people who checked this out. -
Django/Python: Raw SQL Query - Error binding parameter
I'm having a hard time figuring why I'm receiving the below error when the SQL I'm aiming for seems valid. Any ideas? Thank you! sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type. Here's my raw SQL query in question: entries = Entry.objects.raw("SELECT * FROM learning_logs_entry LEFT JOIN learning_logs_document ON (learning_logs_entry.id = learning_logs_document.entry_id) WHERE learning_logs_entry.topic_id = %s AND learning_logs_entry.tag_id IN %s ORDER BY learning_logs_entry.date_added DESC", params=[topic_id, (1,2,3)]) Here's the SQL query produced: SELECT * FROM learning_logs_entry LEFT JOIN learning_logs_document ON (learning_logs_entry.id = learning_logs_document.entry_id) WHERE learning_logs_entry.topic_id = 1 AND learning_logs_entry.tag_id IN (1, 2, 3) ORDER BY learning_logs_entry.date_added DESC Here's my model for both Entry & Tag: class Entry(models.Model): topic = models.ForeignKey(Topic,on_delete=models.CASCADE, related_name='entries') text = models.TextField(validators=[validate_text]) date_added = models.DateTimeField(auto_now_add=True) tag = models.ForeignKey(Tag, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: #metadata verbose_name_plural = 'entries' class Tag(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) -
Pass Seralizer URL params
some context: I am trying to determine which DB to use (every user has its own db) by a given url param. When url is "domain/<identifier>/Guest/" identifier is the url_param i need to pass to the serializer to use that DB I understand i need to override the create(self,validated_data) from the serializer serializer.py class GuestSerializer(serializers.ModelSerializer): def create(self, validated_data): db="???" return models.Guest.objects.using(db).create(**validated_data) class Meta: model = models.Guest fields = "__all__" So i need to pass the url param information to the serializer I'd like to know if there is a better approach -
Slow speeds on AWS S3 bucket upload
I'm using an S3 bucket for my media files on my django project. I've enabled Transfer Acceleration on my s3 bucket and I've also changed these settings from this S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME to S3_URL = '//%s.s3-accelerate.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3-accelerate.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME Unfortunately, these changes have made 0 difference when it comes to my upload speed. From where I am, my upload seems to hit 200kb/s, which is fairly slow. I'm on a 330mbit download / 15mbit upload connection. Questions: Is 200kb/s a good speed for upload to s3? Are there any other obvious or not so obvious things I can check for or change so that my speeds improve? Thanks for your help! -
How to display A only a users entered data related in a foreignkey on detailview in django
I am building this simple quiz app. This app allows all users to submit an answer to an assignment in Docx format. I what that any time a user views the question on the DetailView page, if the user has already submitted a solution for that assignment, that solution should be shown on the DetailView page as well. Current I get is all that answers submitted by all users. I only want a user's answer to that assignment on the detailpage this is my model. class Assignment(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(max_length=500) course = models.ForeignKey(Course, on_delete=models.CASCADE) class_or_level = models.ForeignKey(StudentClass, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) Text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) date_expire = models.DateTimeField() def __str__(self): return self.title class Answer(models.Model): slug = models.SlugField(max_length=500) assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) student = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField(upload_to='assignment') date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} - {} '.format(self.assignment, self.student) Below is my view class AssignmentSubmitView(DetailView): model = Assignment template_name = 'assignment_submit.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['student_answer'] = self.object.answer_set.all() return context Below is my filter on detailview template. {% for answer in student_answer %} {{ answer.file }} {% endfor %} -
How to override the Django generic base View's dispatch method?
If I write a class that inherits from Django's generic base View, what is the correct way to override its dispatch method? The documentation seems to indicate it can be overridden but the example doesn't show exactly how to do it. If I do this, class MyView(View): def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): response = dispatch(request, *args, **kwargs) return HttpResponse('Hello, world!') Django says, NameError: name 'dispatch' is not defined. If I then change the dispatch statement to this, response = self.dispatch(request, *args, **kwargs) Django says, RecursionError: maximum recursion depth exceeded -
Report Lab Printing Values From Forms Rather Than Database
I have a website where users must complete a large questionnaire spread over four webpages (and four forms) and after completing the questionnaire reportlab generates a pdf of their answers. Here is my working code utils.py def generate_pdf(request): # get user user = request.user # get users age born = request.user.personalinformation.dob age = user_utils.get_age(born) doc = SimpleDocTemplate(settings.MEDIA_ROOT+'\pdf_templates\\enrolment_form_%s.pdf' %user.id) styles = getSampleStyleSheet() enrolment_form = [Spacer(1,2*inch)] style = styles["Normal"] page_contents = [ ("Name: %s %s" % (user.personalinformation.first_name, user.personalinformation.surname)), ("Gender: %s" % (user.personalinformation.gender)), ("Age: %s" % (age)) ] for sections in page_contents: p = Paragraph(sections, style) enrolment_form.append(p) enrolment_form.append(Spacer(1,0.2*inch)) doc.build(enrolment_form) models.py class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) GENDERS = ( ('M', 'Male'), ('F', 'Female'), ) first_name = models.CharField(max_length=200, default='') surname = models.CharField(max_length=200, default='') gender = models.CharField(max_length=1, choices=GENDERS) dob = models.DateTimeField('Date of birth (mm/dd/yyyy)', null=True, default=now) def __str__(self): return f'{self.user.username}' (I also have a form.py but dont think its worth including) This works fine, except for fields like 'gender'. Because its getting the values its printing on the pdf from user.personalinformation from the database, instead of printing 'Gender: Male', its printing 'Gender: M'. While this example seems trivial, there are many more fields with key/value pairs and booleans which make no sense printed this way. … -
send_mail() fails with privateemail.com
When I test this code it returns HttpResponse('Invalid header found.'). I'm not sure if this is the best approach for a client. Can't I have it so the client receives the email from the senders email? Rather than using a proxy email to send to their email? That way I don't have to ask them for one of their passwords? forms.py class ContactForm(forms.Form): name = forms.CharField(required=True) from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) views.py def contact_page(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] from_email = form.cleaned_data['from_email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_mail, ['mygmail@gmail.com']) except: return HttpResponse('Invalid header found.') return redirect('main:homepage_view') context = { 'form': form, } return render(request, 'main/contact.html', context) main.contact.html <form method='post' action=''> {% csrf_token %} {{form|crispy}} {{form.errors}} <button type='submit'>Submit</button> </form> settings.py EMAIL_HOST = 'mail.privateemail.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'me@mydomain.com' EMAIL_HOST_PASSWORD = 'myPassword' EMAIL_USE_TLS = True