Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
below code isn't working if condition, how to use if condition under a for loop in python Django
{% for p in products %} {% if p.Category == Category.jam %} <div class="col-xl-4 col-lg-4 col-md-4"> <div class="services-wrapper single-services mb-60"> <div class="services-img"> <div id="carouselExampleIndicatorsOne" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="{{p.image.url}}" alt="First slide"> </div> </div> </div> </div> <div style="padding: 32px 35px 45px 35px;" class="services-text text-center"> <h3><a>{{p.title}}</a></h3> <p style="text-align:left;"> {{p.description}} </p> </div> </div> </div> {% endif %} {% endfor %} the above code executing all categories, it's if statement not checking "category" is "jam" value. -
Class Based Views filtering with "def get_queryset(self):" - Assistance with solving issues
I am trying to filter Data in my Web application and having issues to make it work properly. My application has User model, to whom I assign different programs. Each program contain different exercises. Program Model: class Program(models.Model): patient = models.ForeignKey(User, on_delete=models.CASCADE, default=0) program_name = models.CharField(max_length=1000, default="") date_posted = models.DateTimeField(default=timezone.now) Program View: class ProgramListView(ListView): model = Program template_name = 'program/prog.html' context_object_name = 'programs' def get_queryset(self): return Program.objects.filter(patient=self.request.user) Program Template: {% extends "program/base.html" %} {% block content %} <h3> Please Choose your Program according to your Plan</h3> {% for program in programs %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'program-detail' program.id %}">Program Name - {{ program.program_name }}</a> </div> <p class="article-content">Date Posted - {{ program.date_posted }}</p> </div> </article> {% endfor %} {% endblock content %} Exercise Model: class Exercise(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE, default=0) date_posted = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=1000, default="") description = models.TextField(default="") load_share = models.TextField(default="") breath_method = models.TextField(default="") recovery_method = models.TextField(default="") measure_method = models.TextField(default="") notes = models.TextField(default="") extra_info = models.TextField(default="") reps = models.PositiveSmallIntegerField(default=0) sets = models.PositiveSmallIntegerField(default=0) Exercises View (ProgramDetailView): class ProgramDetailView(DetailView): model = Exercise context_object_name = 'exercises' def get_queryset(self): program_num = get_object_or_404(Program, pk=self.kwargs.get('pk')) return Exercise.objects.filter(program=program_num) Exercises Template: {% extends "program/base.html" %} {% block content %} … -
django celery func.delay dont exetute func
I am working on a django project with 2 apps. I added a celery task in app A and this task calls another method in tasks.py in app B. The method in app B is called as follows send_mail_task_B.delay(subject=subject, from_email=from_email, to_email=to_email, bcc_email=bcc_email, body=body, html_message=html_message) send_email_task_B doesnt get executed with the .delay, but when I remove .delay it executes and sends emails. My __init__.py file in django project conf is as follows: from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app celery_app I am using Django 2.2.8 and celery 4.3.0. I am running celery task in django shell as follows: from A.tasks import send_email_method result=send_email_method_A.apply() -
Need Date Calculation in Django Model
I'm new to django and i'm trying to make laboratory information system with Django. Now i have problem in making modelform for laboratory machines.i fill the quality control interval (e.g. every 3 months) in qc_interval field and fill the starting date of machine in start_op_date field. i want to calculate the dates automatically and send to the qc_dates field for 1 year from date in start_op_date field.i also fill the duration for required calculation in plan_update_interval field. e.g. qc_interval = 3 months start_op_date = 2020-1-31 duration = 12 months qc_dates = [(2020-1-31),(2020-3-31),(2020-6-31),(2020-9-30),(2020-12-31)] ###this is what i want to calculate automatically### From this, i want to make notifications not to pass the quality control dates for our machines. -
(Django Rest Framework) How Do I Update The User Model
I am trying to update the user model (with Django Rest Framework's patch method in APIView) but i keep getting the error. `NotImplementedError: update() must be implemented.` Here is my Serializer: class UpdateSerializer(serializers.Serializer): class Meta: model = User fields = ('email', 'first_name', 'last_name', 'phone') Here is my View: class UpdateUser(APIView): permission_classes = [ permissions.IsAuthenticated, ] def patch(self, request): """ `Update User` """ user = self.request.user serializer = UpdateSerializer(user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I created a custom user model, my serializer for registering users works fine but this update serializer is giving that error -
How to display Selected option value Selected in option tag in Django?
I have Select Option Tag such as <select class="form-control" name="some_name" id="some_name"> {% for newdata in data %} <option value="{{newdata.id}}" {% if "newdata.id==demodata.id" %} selected {% endif %}>{{newdata.name}}</option> {% endfor %} </select> i am Displying option value dynamically using "data" variable. "demodata" is another variable containing values. Now i want to make selected option selected when "newdata.id==demodata.id" this condition is true.However below code is not working <option value="{{newdata.id}}" {% if "newdata.id==demodata.id" %} selected {% endif %}>{{newdata.name}}</option> i don't Know how to do that? -
How to sort DataTable columns by date
I'm using DataTable in my Django application. Everything works fine, but sorting by date is wrong. It's sorting as string, not date. html: <script> $(document).ready(function () { $('.document-table').DataTable({ "order": [ [0, "desc"] ], "bInfo": false, "pagingType": "full_numbers", }); }); </script> -
In Django Datatable server-side processing, can we search for field which is not in database
I have implemented a table in Django showing all data of a particular database. It is server-side processing. from django_datatables_view.base_datatable_view import BaseDatatableView class SearchBar(BaseDatatableView): model = Test order_columns = ['testname', '', 'pass', 'fail'] def get_initial_queryset(self): return Test.objects.all() def filter_queryset(self, qs): search = self.request.GET.get('search[value]', None) if search: qs = qs.filter(testname__icontains=search) return qs def prepare_results(self, qs): json_data = [] i = 0 for item in qs: i += 1 executed = int(item.pass) + int(item.fail) json_data.append([ item.testname, executed , item.pass, item.fail ]) return json_data In the Search box of the data table, (testname, pass, fail) are fields of database Test and hence they are searchable but the field 'executed' is calculated value. How can I make this also as a searchable so that if I type some number and if its present in 'executed' it should also be shown. Or perhaps any external data which will be appended to this table, can it be made searchable in same table? -
Python Django-Rest-Framework update user on data creation
Assuming I have 2 models, one User, the other Post. A user can create posts. A user has a field called 'exp_pts' as an IntegerField. This is meant to increment by say 30 when the user creates a post. I assume I would have to use the create() method in the PostSerializer. This is my current serializer for Posts (currently not working due to the create() method not working as intended) class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'user', 'kingdom', 'post_type', 'file_path', 'title', 'description', 'created_at', 'updated_at') def to_representation(self, instance): data = super().to_representation(instance) data['user'] = SimpleUserSerializer( User.objects.get(pk=data['user'])).data data['kingdom'] = KingdomSerializer( Kingdom.objects.get(pk=data['kingdom'])).data return data # This is not yet working def create(self, validated_data): user = validated_data.pop('user') user.exp_pts += 30 user.save() return user What is a way to do the above? If the create() method isn't adequate then what other way is there to achieve this? Any help much appreciated. Thank you. -
How can I send email reminder before 1 day of an event in Django?
I have three models. CustomUser Webregister Zlink And following is the code for Zlink in models.py, class Zlink(models.Model): customUser = models.ForeignKey(CustomUser, on_delete=models.CASCADE) #foreignkey 1 webregister = models.ForeignKey(Webregister, on_delete=models.CASCADE) #foreignkey 2 reg_link = models.CharField(max_length=255,null=True, blank=True) def __str__(self): return str(self.pk) "foreignkey 2" gives me the event id and "foreignkey 1" gives me an email address of user. Among the many fields, one of the field in Webregister is event_starts that contains date and time of event when it will going to start. I can get the email address of the user in the event using firing the query, x = Webregister.objects.get(id=1) x.customUser Now if the user having multiple users then how these email address to send an email of reminder before a day of event ? Any Clue ? I'm new in django please. -
Apache and Django... Cannot start Django on the server
This question relates to Apache serving Django. Seemingly I cannot start Django app on the server, which is based on Centos 7. I was following this tutorial: https://www.supportsages.com/configure-django-with-apache-in-centos7/ . The instructions how to tight Django to Apache is right at the end of the tutorial. The structure of my Django app is standard: [projectname]/ ├── [projectname]/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py In setting.py: SECURE_HSTS_SECONDS='0' SECURE_HSTS_INCLUDE_SUBDOMAINS=True #SECURE_SSL_REDIRECT=True SESSION_COOKIE_SECURE=True SESSION_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True SECURE_HSTS_PRELOAD=True SECURE_REFERRER_POLICY='None' #or 'same-origine' ALLOWED_HOSTS = [] WSGI_APPLICATION = 'scrap.wsgi.application' STATIC_ROOT = "/path to static/static" STATIC_URL = '/static/' Allowed hosts are in: project/lib64/python3.8/site_packages/django/http/request.py I created: django.conf at the location: /etc/apache2/conf and included it into httpd.conf at the end of the file as: include django.conf django.conf: Alias /static /home/organizations/pro/projects/sc/sc_site/static <Directory /home/organizations/pro/projects/sc/sc_site/static> Require all granted </Directory> <Directory /home/organizations/pro/projects/sc/sc> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess scrap python-path=/home/organizations/pro/projects/sc:/home/organizations/pro/sc_project/lib/python3.8/site-packages WSGIProcessGroup sc WSGIScriptAlias / /home/organizations/pro/projects/sc/sc/wsgi.py I'm totally new to the Server - Apache - Django and most likely missing something obvious... Please let me know if I didn't post some needed information to resolve the question. -
GitHub repository not found during pipenv install
Here in the picture you can see what happened Actually I received the Djoango project from my developer with a virtual environment (pipenv) And when I try to install with his given instructions Like Pipenv install then I got the error GitHub repository not found. during installing dependencies. And a few days ago he solved it by accessing my Mac with anydesk and solved easily like the same steps. And when I try to do same in my other Mac Again after installing some dependencies, it has given me the error GitHub repository not found. Can Anyone tell me what's the real problem? What should I do? -
'JpegImageFile' object has no attribute '_committed' Django ,Pillow
I wanted to take an online image modify it with pillow and returns that modified file on request using Django. I uploaded an image on github and use requests library to get that file. then i added some texts upon it using pillow and returns that file. I tried this import requests from PIL import Image from PIL import ImageFont from PIL import ImageDraw from io import BytesIO def send(request): url='https://github.com/AJITH-klepsydra/images/blob/master/aa.jpg?raw=true' image=requests.get(url).content img = Image.open(BytesIO(image)) font = ImageFont.truetype("arial.ttf", 15) draw = ImageDraw.Draw(img) draw.text((300, 200),"Hello World !",(255,255,255),font=font) return HttpResponse(img, content_type="image/png") but on execution I am getting an error 'JpegImageFile' object has no attribute '_committed' -
How to iterate models.objects.all() in django template when html tags classes are different
models.py class Article(models.Model): title = models.CharField('Title', max_length = 200) text = models.TextField('Descriptiom') pub_date = models.DateTimeField(default=datetime.now(), editable=True) image = models.ImageField(upload_to='images', blank=True) views.py def home(request): articles = Article.objects.all().order_by("-pub_date")[:10] return render(request, 'home.html', {'articles': articles} home.html {% load static %} <hr class="line2"> <a class="other_articles">Другие статьи</a> {% for art in articles %} <rect class="rectangle2_1"> <img src="{{ art.img.url }}" id="rect_img"> <a id="rect_date">{{ art.pub_date }}</a> <p href="#" id="rect_title">{{ art.title }}</p> </rect> <rect class="rectangle2_2"> <img src="{{ art.img.url }}" id="rect_img"> <a id="rect_date">{{ art.pub_date }}</a> <p href="#" id="rect_title">{{ art.title }}</p> </rect> <rect class="rectangle2_3"> <img src="{{ art.img.url }}" id="rect_img"> <a id="rect_date">{{ art.pub_date }}</a> <p href="#" id="rect_title">{{ art.title }}</p> </rect> {% endfor %} Cant iterate through my queryset "articles" in django template, because html classes are different. I know the method: {% for art in articles %} <rect....>art.title</rect> {% endfor %} but it doesn't work for current situation -
DJANGO + SAML2 + CSRF
I have to introduce SAML2 authentication in my Django Project. My base app use CSRF Token that is provided by @ensure_csrf_cookie decorator in the main page. For implementing SAML, I've added a new "login" button on main page (the one that set se csrf token cookie). The button send the SAML request to IDP. When I return from IDP to a landing page (a view in saml2 sub-app that reads the response) I got a 403 Forbidden error about CSRF Token. I'm using OneLogin python Library (python3-saml). https://github.com/onelogin/python3-saml The landing page is the one that ends with: ?acs What I want to know is if its a problem of my landing page or the IDP Response has to be binded with csrf token in some way. Thanks. -
Extracting users from manytomany field from model Django
I want to extract users which are followed by specific user. I have two models here class User(AbstractUser): pass class Follower(models.Model): user = models.ForeignKey(User,null=True, on_delete=models.CASCADE, related_name="follow") following = models.ManyToManyField(User, null=True, blank=True) How to do achieve this in views.py? -
Filtering and Pagination with Django Class Based Views
Looking to add pagination to my view that uses django-filter - to my surprise I found no documentation regarding pagination (which seems should be super common) in this otherwise well-documented package. I did however find several questions on this topic but none have had any clear solutions and even less addressed class-based views. Pagination and django-filter Django Filter with Pagination django-filter use paginations I am following this guide closely but currently stuck (error messages below) https://www.caktusgroup.com/blog/2018/10/18/filtering-and-pagination-django/ urls.py path('trade/', TradeFilteredListView.as_view(), name="trade-list"), filters.py def associated_portfolios(request): associated_portfolios = Portfolio.objects.filter(user=request.user) return associated_portfolios.all() class TradeFilter(django_filters.FilterSet): associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios) date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='last_entry', widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = Trade fields = ['status', 'type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios'] views.py class FilteredListView(ListView): filterset_class = None def get_queryset(self): # Get the queryset however you usually would. For example: queryset = super().get_queryset() # Then use the query parameters and the queryset to # instantiate a filterset and save it as an attribute # on the view instance for later. self.filterset = self.filterset_class(self.request.GET, queryset=queryset) # Return the filtered queryset return self.filterset.qs.distinct() #.filter(user=self.request.user).order_by('last_entry') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Pass the filterset to the template - it provides the form. context['filterset'] = self.filterset_class return context # Attempt @ … -
i am unable to save content of a form in database via Django
hello everyone i am trying to save a form in my database my models.py class customer(models.Model): customerid = models.CharField(default=str(uuid.uuid1()), max_length=500, primary_key=True) customername=models.CharField(max_length=1000,) my forms.py from .models import customer class createcustomerform(ModelForm): class Meta: model=customer fields=['customername'] my views.py def createcustomer(request): if request.method=='GET': return render (request,'marketing/createcustomer.html',{'form':createcustomerform()}) else: try: form=createcustomerform(request.POST) newcreatecustomer=form.save(commit=False) newcreatecustomer.user=request.user newcreatecustomer.save() return redirect('createcustomer') except ValueError: return render(request,'marketing/createcustomer.html',{'form':createcustomerform(),'error':'Check for Invalid Data. Try Again.'}) my html is <form method="POST"> {% csrf_token %} <div id="customernamename"> <span>Company Name</span> <input type="text" id="customername" placeholder="Enter Company's Full name"> </div> </form> When i am clicking save button its redirecting me again to createcustomer but not saving data in my database. kindly help what is wrong or what am i missing ? Its saving the customer by admin area not by html page. -
Django doesn't see css in chrome
Django 3.0 Python 3.8 ubuntu /venv I have default settings.py STATIC_URL = '/static/' and the base.html like this <link href="{% static 'css/base.css'%}" rel="stylesheet" type = "text/css"> path to css file like this myapp/static/css/base.css I used to always do this and it worked. but in this project for some reason does not see chrome / checked in firefox, it works there. -
How to get data for calculated fields in new model django
Im a newbie in Django. I would like to know how can I fill data for calculated fields in a new model. Please help!!! I have 3 models: class StockBalanceSheet(models.Model): finance_year = models.CharField('Finance Year', max_length=90, blank=True, null=True) total_short_and_long_term_assets = models.FloatField('Total Assets', blank=True, null=True, default=0) class StockIncomeStatement(models.Model): finance_year = models.CharField('Finance Year', max_length=90, blank=True, null=True) net_profit_after_tax_parent_company = models.FloatField('Net Profit', blank=True, null=True, default=0) class StockFinanceIndexes(models.Model): finance_year = models.CharField('Finance Year', max_length=90, blank=True, null=True) stock_balance_sheet = models.ForeignKey(StockBalanceSheet, on_delete=models.CASCADE) stock_income_statement = models.ForeignKey(StockIncomeStatement, on_delete=models.CASCADE) roa = models.FloatField('ROA (%)', blank=True, null=True, default=0) @property def get_roa(self): return (self.stock_income_statement.net_profit_after_tax_parent_company / self.stock_balance_sheet.total_short_and_long_term_assets) def save(self, *args, **kwargs): self.roa = self.get_roa super(StockFinanceIndexes, self).save(*args, **kwargs) The data for StockBalanceSheet: 2019 ------ 100 2018 ------ 90 2017 ------ 80 The data for StockIncomeStatement: 2019 ------ 200 2018 ------ 190 2017 ------ 180 Im expecting the data for StockFinanceIndexes based on 2 models: StockBalanceSheet and StockIncomeStatement as the following: 2019 ------ 200/100 = 2 2018 ------ 190/90 = 2.11 2017 ------ 180/80 = 2.25 Thank you a lot!!! -
How to aggregate if the
In django template I could access the price with {% for x in done %} and then access the the product, which is a foreign key to a table about products. So I access the price of the product like this {{x.productt.omzet}}. My question is: How can I sum them up? In views.py I successfully used the aggregate function to sum values from a child table; however, in this case I need to aggregate values from a grand child table. I failed to do that in a for loop at views.py. def factuur(request, id): factuur = Factuur.objects.get(id=id) leerling = Leerling.objects.get(name=factuur.leerling) jezelf = Leerling.objects.get(id=2) paid = BankTransactions.objects.filter(actor=factuur.leerling) total_paid = paid.aggregate(Sum('amount')) done = Product.objects.filter(leerling=factuur.leerling) total_done = done.aggregate(Sum('productt')) if leerling.status == 4: bedrag1 = "done - paid = factuur" elif leerling.status == 3: bedrag1 = "factuur is any" else: bedrag1 = "factuur is niet van toepassing" notice = bedrag1 context = {'factuur': factuur, 'leerling': leerling, 'jezelf': jezelf, 'paid': paid, 'done': done, 'total_paid': total_paid, 'total_done': total_done, 'notice': notice, } return render(request, 'rozendale/factuur.html', context) template: <div class="row"> <div class="col-lg-6"> <table> <tr> <th>Datum</th> <th>Service</th> <th>Bedrag</th> </tr> {% for x in done %} <tr> <td> <a href="/item/{{x.id}}">{{x.date|date:"SHORT_DATE_FORMAT"}}</a> </td> <td> <a href="/product/{{x.productt.id}}">{{x.productt.name}}</a> </td> <td> {{x.productt.omzet}} </td> </tr> {% … -
Automate my task of creating a virtualenv and django
Recently I tried to automate few of my tasks which I perform on daily basis. The task are : go to a specific folder create a virtual environment in that folder go inside the virtual environment folder and then activate the virtual environment install django using pip command I am using subprocess module in python and for now I am able to achieve till step 2 Here is the code : py_sample.py import os import subprocess cwd = os.getcwd() change_dir = os.chdir(cwd) # to create a virtual env virtualenv = input('Enter the name of virtual env : ') #run the python virtualenv command p1 = subprocess.run('python -m virtualenv {}'.format(virtualenv),shell=True) virtualenv = os.path.join(os.getcwd(), virtualenv) #go inside the virtual env folder os.chdir(virtualenv) #activate the virtual environment p2 = subprocess.run(r'.\Scripts\activate.bat',shell=True) cmd C:\Users\swaru\Downloads>python py_sample.py Enter the name of virtual env : django_env created virtual environment CPython3.8.2.final.0-32 in 1423ms creator CPython3Windows(dest=C:\Users\swaru\Downloads\django_env, clear=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\swaru\AppData\Local\pypa\virtualenv) added seed packages: pip==20.1.1, setuptools==49.2.1, wheel==0.34.2 activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator C:\Users\swaru\Downloads>dir/b django_env You can see the virtualenv is created but I am unable to activate the virtualenv. What I am missing here can anyone guide me how to proceed. -
Django error OperationalError, migrations doesnt helped
In my localhost I am getting Django OperationalError and in all stackoverflow questions everybody is talking about python manage.py makemigrations <appname> and python manage.py migrate, but I did the migrations 5 times and I am getting still the same error. Here are my models, views, template and urls file codes. HTML <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'f/ask/ask.css' %}"> <title>BareTalk</title> </head> <body> <div id="wrapper"> <form method="POST"> {% csrf_token %} {{ form }} <!-- TODO: input submit Reg() function javascript --> <input name="final" id="final" type="submit" value="Ask"> </form> </div> </body> <script src="{% static 'f/ask/ask.js' %}"></script> </html> views function view def Answer(request, pk): form = AnswerForm() if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('f')) content = {'form': form} return render(request, 'f/answer.html/', content) models class Answer(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) content = models.TextField('Body', null=True, blank=True, default='Answer') date = models.DateTimeField(default=timezone.now) def __str__(self): return self.content class Meta: verbose_name_plural = 'Answers' verbose_name = 'Answer' urls file urlpatterns urlpatterns = [ # path('', QuestionListView.as_view(), name='f'), path('', index, name='f'), path('<hex:pk>/update/', QuestionUpdateView.as_view(), name='question-update'), path('<hex:pk>/delete/', QuestionDeleteView.as_view(), name='question-delete'), path('new/', QuestionCreateView.as_view(), name='question-create'), path('<hex:pk>/', QuestionDetailView.as_view(), name='current'), path('<hex:pk>/answer', Answer, name='answer') ] and the Django … -
How to get complete contact form information in Django?
This is my code: setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my email@gmail.com' EMAIL_HOST_PASSWORD = 'myemail password' EMAIL_PORT = 587 EMAIL_USE_TLS = True forms.py class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea, required=True) views.py def contact(request): form = ContactForm if request.method == 'POST': form = ContactForm(data=request.POST) if form.is_valid(): sender_name= form.cleaned_data['name'] sender_email= form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message']) try: send_mail('New Enquiry', message, sender_email, ['my email@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') messages.success(request, "Your message has ben sent. Thank you for your interest.") return render(request, 'contact.html', {'form': form}) But the sender's email is not displayed inside the email , I want the sender's email to be both at the (from:) and in the text of the message, Thanks for your help image contact test -
RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it
I am trying to run pytest and am getting this error: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I have the following test in test_models.py that checks if the uuid has been added to the User (it is on autoadd): import pytest from backendapps.core.models import User pytestmark = pytest.mark.django_db class TestUserModel(): user = User.objects.create() assert user.uuid is not None I also have a fixtures file called conftest.py at the root level. import pytest from backendapps.core.models import Org, User @pytest.fixture(autouse=True) def enable_db_access(db): pass I then also have this pytest.ini also at the root level: [pytest] testpaths = backendapps addopts = --ds=config.settings.local --reuse-db --create-db python_files = tests.py test_*.py *_tests.py``` My test database is set to: 'TEST': { 'NAME': 'project_test_db', }, Going through other posts, here are the debug steps I have taken: add the pytestmark = pytest.mark.django_db line - I have this Check the db permissions - my user has superuser permissions Check for migration errors on your db - I migrated all my migrations to zero and reran them to check if I had any manual settings when I migrated and it was all fine. Any thoughts on what to …