Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form is getting wrong instance
I have a view where I list a bunch of child objects belonging to the parent object. Each child's object has a form in the template where they can update their feeling. However, the instance of the form is not showing the correct value. The view looks like this right now: def child_page(request, pk=None): parent = Parent.objects.get(pk=pk) children = Children.objects.filter(parent=parent, user=request.user) form = ChildForm(request.POST or None) if request.POST: child_id = request.POST.get('child_id', None) child_feeling = request.POST.get('feeling') child.feeling = child_feeling child.save() return redirect('index') context = { 'children': children, 'form': form } return render(request, 'test.html', context) I tried to for loop through the child objects and giving the instance like this: for x in children: print(x) form = ChildForm(request.POST or None, instance=x) Which did neither work. The output of the print is all the existing objects. I can't understand why this is happening. With this method, the last elements instance is being showed in all elements instance. How should I get the instance of a single child object and pass it in as the instance, so that each form shows the instance belonging to the child object that is trying to be updated? -
starting a django project
Im brand new to django and am wondering if i could get some help, Im working my way through the guide on the django website and have got to the point of starting a new project with ...\> django-admin startproject mysite after running this command in the terminal I get back an error saying django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoun dException + FullyQualifiedErrorId : CommandNotFoundException Im not a huge fan of the windows terminal and try my best to understand the errors it throws at me but cant. could someone help me out with this please. -
Recursive sql query for django M2M
I need help writing a recursive sql command that will be used as a function (get_children) when a M2M is used. models.py class ConditionGroup(models.Model): name = models.CharField(max_length=100, unique=True) child_groups = models.ManyToManyField( "self", related_name="parent_groups", blank=True, symmetrical=False ) def get_children(): query = """ WITH RECURSIVE parents AS ( SELECT data_collector_conditiongroup.*, 0 AS relative_depth FROM data_collector_conditiongroup WHERE id = %s <<HELP>> ) ORDER BY relative_depth; """ return self.Meta.model.objects.raw(query, [self.id]) Then add the following data: _unrelated_sub_group = ConditionGroup.objects.create(name="unrelated_sub") _unrelated_group = ConditionGroup.objects.create(name="unrelated") _unrelated_group.child_groups.add(_unrelated_sub_group) sub_group_a_1 = ConditionGroup.objects.create(name="sub_group_a1") group_a1=ConditionGroup.objects.create(name="group_a1") group_a1.child_groups.add(sub_group_a_1) group_a=ConditionGroup.objects.create(name="group_a") group_a.child_groups.add(group_a1) sub_group_b = ConditionGroup.objects.create(name="sub_group_b") group_b = ConditionGroup.objects.create(name="group_b") group_b.child_groups.add(sub_group_b) group=ConditionGroup.objects.create(name="group_a") group.child_groups.add(group_a) group.child_groups(group_b) This can be looked at as unrelated unrelated_sub group group_a group_a1 group_b What I need is a recursive sql function in Django such that when I query for the id of "group" it results in a queryset containing group, group_a, group_a1, group_b -
Django REST Framework | many-to-many relation returning "detail: not found"
I'm using Django REST framework. I've created a model for items in an inventory system and also a through table (named subassembly) for many-to-many relationship between items themselves, so an item can be a subpart of other items and vice versa. I'm just not sure I've done it right and I can't seem to get any results. When I visit the backend at a URL such as http://localhost:8000/api/subassemblies/2/, the response is {"detail": "Not found."} but I'm hoping to see all of an item's subparts, or "children". PUT or any other type of request has the same outcome. If it matters, when accessing the subassemblies from the admin page, I can create relationships between items just fine. But only one at a time though. And I need to be able to edit all of an item's subparts in one go (at least, frontend-wise). Currently, the request body is structured like so: { "parent_id": 2, "children": [ { "child_id": 5, "qty": 2 }, { "child_id": 4, "qty": 3 }, ] } This also allows me to use .set() on a particular items children which is useful because I think it also removes any prior children that are not included in the new … -
Run middleware for specific links
do I'm trying to write the code for a social media website. I need every use link to be checked, for e.g. if the user has no followers, turn the number to 0, and if it has no followings, turn it back to 0. it works fine for certain users, but creates issues with some other ones, I will put my code below. *UserFollowing is a model which determines who follows who. models: `class UserFollowing(models.Model): user = models.ForeignKey(User, related_name="following",on_delete=models.CASCADE) following_user= models.ForeignKey(User, related_name="followers",on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True)` URLS: from django.urls import path from . import views from.views import CreatePost urlpatterns = [ path('explore/', views.Listexplore.as_view(), name='page-explore'), path('user/<str:username>/', views.UserList.as_view(), name='user-posts'), path('post/<int:pk>/', views.DetailPost.as_view(), name='post-detail'), path('post/<int:pk>/update/', views.UpdatePost.as_view(), name='post-update'), path('post/<int:pk>/delete/', views.DeletePost.as_view(), name='post-delete'), path('post/create/', CreatePost.as_view(), name='post-create'), path('about/',views.about,name='page-about'), path('home/',views.Listhome.as_view(),name='page-home'), path('tests/',views.test,name="page-test"), ] view: def post(self, request,**kwargs): user2 = get_object_or_404(User, username=self.kwargs.get("username")) try: UserFollowing.objects.get(following_user=user2, user=request.user) created = UserFollowing.objects.get(following_user=user2, user=request.user) created.delete() request.user.profile.follower -= 1 user2.profile.following -= 1 request.user.save() user2.save() except UserFollowing.DoesNotExist : created = UserFollowing.objects.create(following_user=user2, user=request.user) request.user.profile.follower += 1 user2.profile.following += 1 created.save() request.user.save() user2.save() return redirect(request.META['HTTP_REFERER']) def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get("username")) return post.objects.filter(author=user).order_by("-time") def get_context_data(self, **kwargs): context = super(UserList, self).get_context_data(**kwargs) context['user2'] = get_object_or_404(User, username=self.kwargs.get("username")) my_user= User.objects.get(username=self.request.user.username) try: UserFollowing.objects.get(following_user=context['user2'], user=my_user) follow=True except UserFollowing.DoesNotExist : follow=False context['follow']=follow return context the middleware i wrote: … -
How do i create a direct message in django channels
I have watched a couple of tutorials on Django channels but i can't figure out how to create a direct message in my website. Every tutorial's always creating a room and then adding multiple users. I want to build a message system whereby users can message other users i.e only 2 participant. Like a p2p message -
How to correctly configure Gmail to send E-mail with Django. The official configuration does not work for me
I am preparing an online portfolio made with Django and one of the features is a form with which you can contact me via E-mail. To verify that this functionality worked correctly, I have been testing it with MailTrap and it works perfectly, now for the production version I want the E-mails to reach my Gmail mail, but despite the fact that in theory I have followed all the steps, no I get it to work, it only worked for me with MailTrap. In my Gmail account I already activated two-step verification and created a specific password for the application. The lower security option apparently does not exist since May of this year. This is the configuration of my Settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "my-e-mail@gmail.com" EMAIL_HOST_PASSWORD = 'smbumqjiurmqrywn' EMAIL_PORT = 587 EMAIL_USE_TLS = True This password is just an example, it is just to show how it is set. And this is the method to send the E-mail. I am using EmailMessage but with send_mail the result is the same: def contact(request): contact_form = ContactForm() if request.method == 'POST': contact_form = ContactForm(data = request.POST) if contact_form.is_valid(): name = request.POST.get('name', '') email = request.POST.get('email', '') content = … -
Unexpected Keyword Argument in Django forms
The error that I am getting is: TypeError at /newapplicantregisteration/ newapplicantregisteration() got an unexpected keyword argument 'applicantname' I a m trying to create a form and pass input data to the backend. What can I do -
Javascript Counting Occurrences Based on Django For Loop
Hi I was wondering if someone could help me figure out how to count the number of occurrences of a word in a django array. For instance, this array currently returns [Train, Car, Car, Train, Motorcycle, Plane]. I want it to return that Train appears 3 times, Car 2 times, etc. If anyone can help it would be greatly appreciated! Thanks. <script> let distribution = document.querySelectorAll(`[id^="distribution"]`) const shipment = Array.from(document.querySelectorAll('.method-of-shipment')); const shipment_inner = shipment.map((element) => element.innerText); function countOccurrences(str,word) { // split the string by spaces in a let a = str.split(","); // search for pattern in a let count = 0; for (let i = 0; i < a.length; i++) { // if match found increase count if (word==(a[i])) count++; } return count; } // Driver code let str = shipment_inner; let word = "Train"; distribution.innerText = document.write(countOccurrences(str, word)); </script> <div> {% for loans in loans_in_securities %} <a class="method-of-shipment">{{loans.method_of_shipment}}</a> {% endfor %} <br> <a id="distribution"></a> </div> -
How to save formsets in django
I want to add multiple forms when a button is clicked and I am using formsets to accomplish that but when I try to save the forms it doesn't give an error bu does not save it either. my views.py: def StepThreeView(request): formSet = modelformset_factory(Club, fields=("name", "channel", "logo", "created_by")) form = formSet(queryset=Example.objects.none()) if (request.method == "POST"): form = formSet(request.POST) if (form.is_valid()): form.save() context = { 'form': form } return render(request, 'on_boarding/step_three.html', context) my html: <form method="POST" id="form"> {% csrf_token %} {{ form.management_form }} <div class="hidden" id="form-copy"> {{ form.empty_form.as_p }} </div> </form> <button class="add-club" type="button" onclick="AddUser()"> Add user </button> my javascript: function AddUser() { const formCopyTarget = document.getElementById("formCopyTarget"); const copyForm = document.getElementById("form-copy").cloneNode(true) const totalNewForm = document.getElementById('id_form-TOTAL_FORMS') const currentForms = document.getElementsByClassName("block") let totalForms = currentForms.length copyForm.setAttribute('class', 'block') copyForm.setAttribute('id', `form-${totalForms}`) const regex = new RegExp('__prefix__', 'g') copyForm.innerHTML = copyForm.innerHTML.replace(regex) totalNewForm.setAttribute('value', totalForms + 1) formCopyTarget.append(copyForm) } -
How to show choices fields in django admin?
I have a model with a lot of fields, Some fields are Char type with choices https://docs.djangoproject.com/en/dev/ref/models/fields/#choices These fields don't display in the admin panel list_display I generate like this list_display = [field.name for field in Event._meta.get_fields()] How to change the generation of the list, so that fields with type choices are shown ? Thanks in advance -
How can I count overall how many reviews are in an author's all posts?
I building an e-Commerce website, here also has a system of merchandiser accounts. Every merchandiser can upload their product photo with all information for selling. A merchandiser can sell different types of products. Buyers can give product reviews on the product they bought. Now I want to show the overall total of how many buyers have given feedback on seller products. For example: seller-1: 10 reviews, 4.5 star, seller-2: 5 reviews, 4.8 star, seller-3: 11 reviews, 4.1 star. How can I do it? Please help me😢... models.py: class Products(models.Model): user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True) product_title = models.CharField(blank=True, null=True, max_length = 250) brand = models.CharField(max_length=250, blank=True, null=True) product_desc = RichTextField(blank=True, null=True) class ProductREVIEWS(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userREVIEW',on_delete=models.CASCADE) product = models.ForeignKey(Products, related_name='productREVIEWrelatedNAME',on_delete=models.CASCADE) feedBACK = models.TextField(blank=True, null=True) rating = models.IntegerField(blank=True, null=True) -
How to establish a tcp connection through a proxy ip in python?
I need to connect to a server that periodically sends text data over a TCP connection, and the server needs my IP to be static. My backend (Django) is hosted on Heroku (dynamic IPs), but I have an add-on service that provides me with the static IPs (whitelisted by the target server). How do I route the TCP connection through a proxy IP? -
Select 2 query and Bootstrap 5
para las model de boostrap 5 se debe agragar las siguientes lineas para que funcione correctamente : jQuery(document).ready(function($){ $(document).ready(function() { $('#id_select').select2({ width: '100%', dropdownParent: $('.modal-body','#mymodel') }); }); }); -
How to render my function in html in Django
please excuse me in advance in case that my question has been answered many times before. Cause I'm new to django, I just don't have a clue which keyword I have to search with. I made a countdown timer which works well in the console. The function display a clock(remaining days:hours:mins:secs) decrementing a sec until the end. def countdown(): dt = get_delta() while dt > 0: d = calculation(dt)['day'] h = calculation(dt)['hour'] m = calculation(dt)['min'] s = calculation(dt)['sec'] countdown.timer = '{:02d} days {:02d} hours {:02d} mins {:02d} secs'.format(d, h, m, s) print(countdown.timer, end='\r') time.sleep(1) dt -= 1 countdown.boom = "--------Happy birthday!--------" print(countdown.boom) What I want to do is to render this part on my webpage built by django. countdown.timer = '{:02d} days {:02d} hours {:02d} mins {:02d} secs'.format(d, h, m, s) This is my render function part: def index(request): context = {'timer': countdown.timer} return render(request, 'MainApp/index.html', context) I tried to pass countdown.timer variable or countdown() function itself to my django template. <div class="container-fluid" style="background-color: black"> <div class="rows"> <div class="col-md-12"> <article> <h1>This is where my timer is.</h1> <p>{{ timer }}</p> </article> </div> </div> </div> It doesn't feel right and it didn't work but I don't know how to get it done. … -
Django-compressor not finding blocks to compress in a GitHub Action
I have a Django project that's using django-compressor to minify and concatenate CSS files, using offline compression. I haven't yet put it on a server, but when I run manage.py compress in a GitHub Action, before running tests, it can't find the {% compress %} block, even though it can find the template containing them. I have a single template that uses CSS files, templates/myapp/layouts/base.html: <!DOCTYPE html> {% load compress static %} <html lang="en"> <head> <!-- ... --> {% compress css file global %} <link rel="stylesheet" href="{% static 'oohdir/css/global/variables.css' %}"> <link rel="stylesheet" href="{% static 'oohdir/css/global/reset.css' %}"> <link rel="stylesheet" href="{% static 'oohdir/css/global/form.css' %}"> <!-- etc --> {% endcompress %} When running the site locally I can have these Django settings: DEBUG = False COMPRESS_ENABLED = True COMPRESS_OFFLINE = True and when I run manage.py compress it generates a single CSS file, as expected, in static_collected/CACHE/CSS/. That file is linked in the HTML when I view pages in the browser (using manage.py runserver --insecure). But when I run my GitHub Action many tests fail because of a missing file, which django-compressor didn't generate. If I run manage.py compress --verbosity 2 in the Action I can see it finds the correct template among … -
Django: problem trying to post data to django model database
ProgrammingError at /admin/formRegister/formregister/ column formRegister_formregister.password1 does not exist LINE 1: ...astname", "formRegister_formregister"."username", "formRegis... ^ Request Method: GET Request URL: http://localhost:8000/admin/formRegister/formregister/ Django Version: 4.0.5 Exception Type: ProgrammingError Exception Value: column formRegister_formregister.password1 does not exist LINE 1: ...astname", "formRegister_formregister"."username", "formRegis... ^ Exception Location: C:\Users\hp\Desktop\Django\django3.9\lib\site-packages\django\db\backends\utils.py, line 89, in _execute Python Executable: C:\Users\hp\Desktop\Django\django3.9\Scripts\python.exe Python Version: 3.9.13 Python Path: ['C:\Users\hp\Desktop\Django\teluskoa', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\python39.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\hp\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\Users\hp\Desktop\Django\django3.9', 'C:\Users\hp\Desktop\Django\django3.9\lib\site-packages'] Server time: Thu, 11 Aug 2022 16:02:26 +0000 -
resource objects need to have a primary key value before you can access their tags
I am using django-taggit. When i used pre-save signal then I got the error below. resource objects need to have a primary key value before you can access their tags. model.py class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) varient=models.CharField(max_length=100, default="") Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(default="", unique=True, blank=True) Tags = TaggableManager(blank=True) pre-save signal function is def tag_set(sender, instance, **kwargs): print(instance.Tags) pre_save.connect(tag_set, sender=resource) -
Django prefetch_related multiple fields
Let's assume I have the following model class Store: name = models.CharField() location = models.CharField() clients = models.ManyToManyField('Client', related_name='stores', on_delete=models.CASCADE) providers = models.ManyToManyField('Provider', related_name='stores', on_delete=models.CASCADE) rating = models.CharField(max_length=128, choices=Rating.choices(), blank=True) I am aware I can do something like Store.objects.all().prefetch_related('clients') to prefetch the clients; however, I need to prefetch for providers as well, I could write to different queries, but I am wondering if I can something like Store.objects.all().prefetch_related('clients', 'providers') Additionally, what would be the best way to group them by rating? There might be betters way to this, any feedback is more than welcome. Thank you all!! -
I am getting this error in context_processors 'NoneType' object is not iterable
I want to show messages in every template that's why I need a context processor. But I am getting this error 'NoneType' object is not iterable. I can not resolve this problem. Can anyone see the code and give a solution for it. # context_processors.py from django.contrib import messages from .models import Loan def message_notification(request): loan_requested_lists = Loan.objects.filter(loan_req_user=request.user, active=True, status='Pending') if loan_requested_lists.exists(): if loan_requested_lists.count() == 1: for i in loan_requested_lists: return messages.info(request, f'{i.user.username}({i.user.account_number}) was requested for loan.') else: return messages.info(request, f'{loan_requested_lists.count()} users were requested for loan.') This is my models.py from django.utils import timezone from django.db import models from accounts.models import User from django.core.exceptions import ValidationError # Create your models here. STATUS = ( ('Pending', 'Pending'), ('Accepted', 'Accepted') ) EDITABLE_STATUS = ( ('Not Applicable', 'Not Applicable'), ('Requested', 'Requested'), ('Approved', 'Approved'), ('Not Approved', 'Not Approved'), ('Updated', 'Updated'), ) def validate_date(date): if date < timezone.now(): raise ValidationError("Date cannot be in the past") class Loan(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) loan_req_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='loan_given_user_list', verbose_name='Loan Requested From User') amount = models.PositiveIntegerField(verbose_name='Loan Amount') date = models.DateTimeField(default=timezone.now, validators=[validate_date], verbose_name='Loan Return Date') status = models.CharField(max_length=8, choices=STATUS, default='Pending') editable = models.CharField(max_length=14, choices=EDITABLE_STATUS, default='Not Applicable') active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True, verbose_name='Loan Requested Date') def __str__(self): return self.user.username -
Send email with attach in python error under https
i have an error trying to send email with attach pdf in python (Django) under https active but not do under http, this is my code: from django.conf import settings import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders sender_email_address = sender@mail.com email_password = myPass email_smtp = smtp.gmail.com email_subject = self.titulo receiver_email_address = receiver@gmail.com remitente = sender_email_address destinatarios = [receiver_email_address] asunto = email_subject cuerpo = self.cuerpo ruta_adjunto = 'file.pdf' nombre_adjunto = 'file.pdf' mensaje = MIMEMultipart() mensaje['From'] = remitente mensaje['To'] = ", ".join(destinatarios) mensaje['Subject'] = asunto mensaje.attach(MIMEText(cuerpo, 'plain')) archivo_adjunto = open(ruta_adjunto, 'rb') adjunto_MIME = MIMEBase('application', 'octet-stream') adjunto_MIME.set_payload((archivo_adjunto).read()) encoders.encode_base64(adjunto_MIME) adjunto_MIME.add_header('Content-Disposition', "attachment; filename= %s" % nombre_adjunto) mensaje.attach(adjunto_MIME) sesion_smtp = smtplib.SMTP(email_smtp, '587') sesion_smtp.set_debuglevel(1) sesion_smtp.ehlo() sesion_smtp.starttls() sesion_smtp.login(sender_email_address, email_password) texto = mensaje.as_string() sesion_smtp.sendmail(remitente, destinatarios, texto) sesion_smtp.quit() -
Django debug toolbar loads but doesn't show on the local server even after proper installation
I have installed django debug toolbar correctly on a pipenv environment and done the main steps, such as adding internal_ips of 127.0.0.1 and adding the debug toolbar to installed_apps and middleware but still whenever I run the server and open a template of an app the debug toolbar doesn't show. However if I open the page source in the browser, it shows all the elements of the toolbar however the toolbar doesn't display, does anyone know what is going wrong and how I could fix it. -
Filtering data from 3 different tables in django with 1 intermediate table
I have four models in my django application with following structure: class User(models.Model): first_name = models.CharField() last_name = models.CharField() class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class SomeItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class SomeOtherItem(models.Model): some_item = models.ForeignKey(SomeItem, on_delete=models.CASCADE, unique=True) I have to create an API and I have been given a list of SomeItem. I have to write a django queryset line to filter first_name and last_name from User model, all details of SomeItem model and all details of SomeOtherItem model(if present). I also have to create a serializer to parse the data as a Python dict. Will be great if one can help me in this. -
"detail": "Authentication credentials were not provided." in django rest framework
I am trying to do an app on flutter with django rest framework backend. I want to log in as an already registered user and then I want to see only my active tasks, because further I want to end them after some time. The problem is I get "detail": "Authentication credentials were not provided." when I have made some changes in my code. I do the authentification with username and password. views.py class LoginAPI(APIView): def post(self, request): username = request.data['username'] password = request.data['password'] user = User.objects.filter(username=username).first() Token.objects.create(user=user) if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') payload = { 'id': user.id, #'username': user.username, #'password': user.password } token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8') response = Response() response.set_cookie(key='token', value=token, httponly=True) response.data = { 'token': token } print(user.id) return response class seeActiveTasks(ListAPIView): queryset = Tasks.objects.filter(is_active = 1) serializer_class = taskSerializer permission_classes = [IsAuthenticated] def get_queryset(self): print(self.request.user) print(self.request.user.id) # added string #return super().get_queryset().filter(user=self.request.user.id) return super().get_queryset().filter(user_id = self.request.user.id) login_page.dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; import 'package:phoneapp/main.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:phoneapp/screens/get_tasks.dart'; class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { bool _isLoading = false; @override Widget build(BuildContext context) { … -
Pytest does not raise ValidationError
I'm trying to test that a user can't be both agent and organizer but pytest doesn't raise ValidationError. models.py class User(AbstractUser): email = models.EmailField(unique=True) is_organizer = models.BooleanField(default=False) is_agent = models.BooleanField(default=False, ) def clean(self): super().clean() if self.is_organizer and self.is_agent: raise ValidationError("User can't be Agent and Organizer at the same time") test @pytest.mark.django_db() def test_user_cant_be_organizer_and_agent_at_the_same_time(): # user = User(username='ali', email='ali@gmail.com', password='a.123456', is_agent=False, is_organizer=True) # user.full_clean() with pytest.raises(ValidationError): User(username='a', email='a@gmail.com', password='a.123456', is_agent=True, is_organizer=True) pytest error core\tests\test_users.py:21 (test_user_cant_be_organizer_and_agent_at_the_same_time) @pytest.mark.django_db() def test_user_cant_be_organizer_and_agent_at_the_same_time(): # user = User(username='ali', email='ali@gmail.com', password='a.123456', is_agent=False, is_organizer=True) # user.full_clean() with pytest.raises(ValidationError): > User(username='a', email='a@gmail.com', password='a.123456', is_agent=True, is_organizer=True) E Failed: DID NOT RAISE <class 'django.core.exceptions.ValidationError'> test_users.py:28: Failed Destroying test database for alias 'default' ('test_crm')...