Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'WSGIRequest' object has no attribute 'is_ajax' (is_ajax has been defined in the views.py file)
I have included the following is_ajax() function, so that I can use it in another Django view function in the same views.py file: def is_ajax(request): return request.META.get(‘HTTP_X_REQUESTED_WITH’) == ‘XMLHttpRequest’ However, the problem is that I am still getting the following error message in the terminal: AttributeError: ‘WSGIRequest’ object has no attribute ‘is_ajax’ The following image shows the views.py file where the is_ajax() function is being called on line 48: is_ajax() function in the views.py file line 48 I will appreciate any suggestions on how to resolve this issue. Thank you. -
check_token() methon requesting for token argument yet it has been passed
I have been trying to create a reset password feature on my project I have been able to successfully send the reset password link to the email but am having trouble verifying the link sent. I am using the check_token method from PasswordResetTokenGenerator but I keep getting this error check_token() missing 1 required positional argument: 'token'. Yet I have passed both required argument bellow is my Error and code: Error Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\User\Documents\vend\vendbackend-master\authentication\views.py", line 146, in get if not PasswordResetTokenGenerator.check_token(user,token): Exception Type: TypeError at /api/authentication/password-reset/Mjk/b8a8se-b3e01964eb0d0f76a20c9418c9890a8b Exception Value: check_token() missing 1 required positional argument: 'token' views.py class RequestPasswordReset(generics.GenericAPIView): serializer_class = RequestPasswordResetSerializer permission_classes = (permissions.AllowAny,) def post(self, request): data = {'request':request, 'data':request.data} serializer = self.serializer_class(data) email = request.data.get('email') if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) uidb64=urlsafe_base64_encode(smart_bytes(user.id)) … -
How to hide entire row if one or two fields are empty Django
How can I hide an entire row if one or more specific fields are empty? For example, I have a django query set up so that I can get a total profit from items in the inventory manager. The way that I have that written is like: html {% extends 'portal/base.html' %} {% block title %}Inventory{% endblock %} {% block content %} <br> <div class="row"> <div class="col"> <form class="d-flex" role="search" action="/search" method="get"> <input class="form-control me-2" type="text" name="q" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success">Search</button> </form> </div> <div class="col"> <a class="btn btn-primary me-md-2" href="/newitem" type="button">Input New Purchase</a> </div> </div> </div> <table class="table table-striped"> <thead> <tr> <th>Breakdown</th> <th>Product ID</th> <th>Product</th> <th>Total Profit</th> </tr> </thead> {% for inventory in inventory %} <tr> <td><a class='btn btn-success btn-sm' href=''>View Breakdown</a> <td>{{inventory.id}}</td> <td>{{inventory.product}}</td> <td>{{ inventory.Calculate_profit }}</td> </tr> {% endfor %} </table> {% endblock %} views.py @property def Calculate_profit(self): soldfor = Inventory.objects.filter(soldprice=self.soldprice).aggregate(Sum('soldprice'))['soldprice__sum'] or 0.00 paidfor = Inventory.objects.filter(paid=self.paid).aggregate(Sum('paid'))['paid__sum'] or 0.00 shipfor = Inventory.objects.filter(shipcost=self.shipcost).aggregate(Sum('shipcost'))['shipcost__sum'] or 0.00 totalprofit = soldfor - paidfor - shipfor return totalprofit As long as the model fields soldprice , paid , and shipcost are all filled out on every row in the database, I can get the results no problem. I get an error if soldprice or … -
Django code user querry does not exists. Kindly help me
enter image description here the code is throwing error by saying ht user querry not exists . -
How to setup 2 django virtual environment in 1 apache server
Environment: Apache: 2.4 Python 3.7.2 (32bit) 1st Django: 2.1.15 2nd Django: 3.2.11 System: Windows Server 2016 Database: SQL Server 2016 I'm a newcomer in Apache and I want to add a new Django project (3.2.11) on an Apache server, which has been served an other Django project (2.1.15) for a long time. After checking some tutorial on the internet, I still can let only one Django project available, below are my configurations: file: httpd.conf Listen *:1111 Listen *:2222 active LoadModule vhost_alias_module modules/mod_vhost_alias.so active Include conf/extra/httpd-vhosts.conf file: httpd-vhosts.conf LoadFile "C:/Program Files (x86)/Python37-32/python37.dll" LoadModule wsgi_module "d:/django_project1/env1/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win32.pyd" WSGIPythonHome "d:/django_project1/env1/" #WSGIPythonHome "d:/django_project2/env2/" <- I can't active both WSGIPythonHome at same time. <VirtualHost *:1111> ServerName http://10.198.170.91 ServerAlias http://10.198.170.91 WSGIScriptAlias / D:/django_project1/web_project/web_project/wsgi_windows.py <Directory D:/django_project1/web_project/web_project> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /static D:/django_project1/web_project/apps/static <Directory D:/django_project1/web_project/apps/static\> AllowOverride None Options None Require all granted </Directory> DocumentRoot "D:/django_project1/web_project" <Directory "D:/django_project1/web_project"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> ErrorLog "logs/django_project1-error.log" CustomLog "logs/django_project1-access.log" common </VirtualHost> <VirtualHost *:2222> ServerName http://10.198.170.91 ServerAlias http://10.198.170.91 WSGIScriptAlias / D:/django_project2/web_project/web_project/wsgi_windows.py <Directory D:/django_project2/web_project/web_project> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /static D:/django_project2/web_project/apps/static <Directory D:/django_project2/web_project/apps/static\> AllowOverride None Options None Require all granted </Directory> DocumentRoot "D:/django_project2/web_project" <Directory "D:/django_project2/web_project"> Options Indexes FollowSymLinks AllowOverride None Require all granted … -
Trying to subtract two fields and keep getting errors in Django and Postgresql
I am trying to subtract two fields from a model. For example, "Soldfor" is assigned 55 and "Paidfor" is assigned 1.99 in the database. I am trying to get the two fields to subtract from each other to get a total profit for each item in the database. Below is my code: model.py @property def Calculate_profit(self): soldfor = Inventory.objects.filter(self.soldprice).aggregate(Sum('soldprice'))['soldprice__sum'] or 0.00 paidfor = Inventory.objects.filter(self.paid).aggregate(Sum('paid'))['paid__sum'] or 0.00 totalprofit = soldfor - paidfor return totalprofit Whenever that I load the HTML document, I get this error : "TypeError at /profitsperitem cannot unpack non-iterable decimal.Decimal object". I can get it to work if I set it to .all(). with no filters, but then that will repeat the same payout number for each item. view.py @login_required(login_url="/login") def profitsperitem(request): inventory = Inventory.objects.all().order_by('id') return render(request, 'portal/profitsperitem.html', {"inventory": inventory}) html {% extends 'portal/base.html' %} {% block title %}Sulley Sells Inventory{% endblock %} {% block content %} <br> <div class="row"> <div class="col"> <form class="d-flex" role="search" action="/search" method="get"> <input class="form-control me-2" type="text" name="q" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success">Search</button> </form> </div> <div class="col"> <a class="btn btn-primary me-md-2" href="/newitem" type="button">Input New Purchase</a> </div> </div> </div> <table class="table table-striped"> <thead> <tr> <th>Breakdown</th> <th>Product ID</th> <th>Product</th> <th>Total Profit</th> </tr> </thead> {% for inventory … -
RuntimeError: 'empty_form' is not used in polymorphic formsets, use 'empty_forms' instead
I am developing a django api project based on the django rest framework. I have 3 models: class Level(PolymorphicModel): name = models.CharField(null=True, blank=True, max_length=25, verbose_name="название") description = models.TextField(null=True, blank=True, verbose_name="описание") module = models.ForeignKey(Module, null=True, blank=True, verbose_name='модуль', db_column='module_id', on_delete=models.CASCADE, related_name='levels') next_level = models.ForeignKey('self', null=True, blank=True, verbose_name='следующий уровень', db_column='next_level_id', on_delete=models.SET_NULL) def __str__(self): return f'{self.name}' class Meta: # abstract = True db_table = 'level' verbose_name = "уровень" verbose_name_plural = 'уровни' class Puzzle(Level): time = models.PositiveIntegerField(null=False) class Test(Level): time = models.IntegerField(null=True, blank=True, verbose_name='время на прохождение теста') class Meta: db_table = 'test' verbose_name = "тест" verbose_name_plural = "тесты" and Admin models: from django.contrib import admin from polymorphic.admin import StackedPolymorphicInline, PolymorphicInlineSupportMixin, PolymorphicChildModelAdmin, PolymorphicParentModelAdmin from .models import * # Register your models here. @admin.register(Test) class TestAdmin(PolymorphicChildModelAdmin): base_model = Test @admin.register(Puzzle) class PuzzleAdmin(PolymorphicChildModelAdmin): base_model = Puzzle @admin.register(Level) class LevelAdmin(PolymorphicParentModelAdmin): base_model = Level child_models = (Test, Puzzle, ) class LevelInline(StackedPolymorphicInline): class TestInline(StackedPolymorphicInline.Child): model = Test class PuzzleInline(StackedPolymorphicInline.Child): model = Puzzle model = Level #empty_forms = None child_inlines = ( TestInline, PuzzleInline, ) @admin.register(Module) class ModuleAdmin(admin.ModelAdmin, PolymorphicInlineSupportMixin): inlines = (LevelInline,) PolymorphicModelAdmin works fine for me but StackedPolymorphicInline throws this exception. Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/plotbackend/module/1/change/ Django Version: 4.0.5 Python Version: 3.9.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
Why this throws error when I user filter in django
I'm tried this print(request.user.profile.messages.filter(is_read=True).count()) and this print(Message.objects.filter(recipient=request.user.profile,is_read=False)) this is showing this error djongo.exceptions.SQLDecodeError: Keyword: FAILED SQL: SELECT "users_message"."sender_id", "users_message"."recipient_id", "users_message"."sender_name", "users_message"."email", "users_message"."subject", "users_message"."body", "users_message"."is_read", "users_message"."msg_read", "users_message"."created", "users_message"."id" FROM "users_message" WHERE (NOT "users_message"."is_read" AND "users_message"."recipient_id" = %(0)s) ORDER BY "users_message"."is_read" ASC, "users_message"."created" DESC LIMIT 21 Params: (UUID('c7a7c847-cd94-419d-a86c-f8935a2abd80'),) Version: 1.3.6 Sub SQL: None FAILED SQL: None Params: None Version: None The above exception was the direct cause of the following exception: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True,blank=True) name = models.CharField(max_length=200,blank=True, null=True) email = models.EmailField(max_length=400,blank=False,null=True) bio = models.TextField(blank=True,null=True) username = models.CharField(max_length=200,blank=True, null=True) location = models.CharField(max_length=200,blank=True, null=True) short_intro = models.CharField(max_length=200,blank=True,null=True) profile_image = models.ImageField(blank=True,null=True,upload_to='profiles/',default="profiles/user-default.png") social_github = models.CharField(max_length=200,blank=True, null=True) social_twitter = models.CharField(max_length=200,blank=True, null=True) social_linkedin = models.CharField(max_length=200,blank=True, null=True) social_youtube = models.CharField(max_length=200,blank=True, null=True) social_website = models.CharField(max_length=200,blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) class Meta: ordering = ['-created'] def __str__(self): return str(self.user.username) class Message(models.Model): sender = models.ForeignKey(Profile,on_delete=models.SET_NULL, null=True, blank=True) recipient = models.ForeignKey(Profile,on_delete=models.SET_NULL,null=True,blank=True,related_name="messages") sender_name = models.CharField(max_length=200, null=True, blank=True) email = models.EmailField(max_length=200, null=True, blank=True) subject = models.CharField(max_length=200,null=True,blank=True) body = models.TextField() is_read = models.BooleanField(default=False,null=True) msg_read = models.DateTimeField(auto_now_add=True, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) #views.py file def profiles(request): profiles, search_query = searchProfiles(request) custom_paginator, profiles = paginateProfiles(request,profiles,6) if request.user.is_authenticated: try: new_msg_count = request.user.profile.messages.all().filter(is_read=True).count() except: new_msg_count = "" print(request.user.profile.messages.filter(is_read=True).count()) … -
How to use external files for Django tests
I have to test model validation for checking SVG files. Therefore I want to access to my test files but I've stucked with a error SuspiciousFileOperation. I tried get files from app directory, store the files in static folder and use django.contrib.staticfiles.finders.find function to get them but the problem appears again and again. -
Exception Value: NOT NULL constraint failed: auctions_grade.grader_id
I have a model "homework" and a model "grade". I can add new homeworks flawlessly but when I try to grade them using generic class based createview I get "Exception Value: NOT NULL constraint failed: auctions_grade.grader_id". "grader" should be the author/request user (or the professor). Models.py class Hw_upload(models.Model): title = models.CharField(blank=True, max_length=255, null=True) description = models.TextField(blank=True, max_length=255, null=True) document = models.FileField(blank=True, upload_to='documents/', null=True) creation_date = models.DateTimeField(default=timezone.now) hw_author = models.ForeignKey(User, on_delete=models.PROTECT, related_name="hw_author") course_hw_upload = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course_hw_uploads", null=True) module_hw_upload = models.ForeignKey(Module, on_delete=models.CASCADE, related_name="module_hw_uploads", null=True) activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name="hw_uploads", null=True) class Grade(models.Model): score = models.PositiveIntegerField(validators=[MaxValueValidator(100)], blank=True, null=True) comment = models.TextField(max_length=300, null=True) creation_date = models.DateTimeField(default=timezone.now) grader = models.ForeignKey(User, on_delete=models.PROTECT, related_name="grade_author") graded = models.BooleanField(default=False) course_grade = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course_grades", null=True) module_grade = models.ForeignKey(Module, on_delete=models.CASCADE, related_name="module_grades", null=True) activity_grade = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name="activity_grades", null=True) hw_upload = models.ForeignKey(Hw_upload, on_delete=models.CASCADE, related_name="grades") Forms.py class Hw_uploadForm(ModelForm): class Meta: model = Hw_upload fields = ['title', 'description', 'document'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Title'}), 'description': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Body', 'rows':3, 'cols':15}), } class Hw_gradeForm(ModelForm): class Meta: model = Grade fields = ['score'] widgets = { 'score': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0-100'}) } Views.py # Grade homework class GradeView(CreateView): model = Grade template_name = "grading.html" form_class = Hw_gradeForm success_url = reverse_lazy('index') … -
anotmic not working as context manager in django 4
I tried to use transactions in django 4.0.6 as the same in docs: from django.db import transaction def transaction(request): do_stuff() with transaction.atomic(): do_somestuff() But I got error: with transaction.atomic(): AttributeError: 'function' object has no attribute 'atomic' It works in django 3.2.4. What's the problem with django 4? Thank you! -
django rest framework api key How to set view/endpoint permissions by apikey?
I am using django "rest framework api key"; I have urls in my urls.py (I'll try to keep it simple): a/ b/ c/ and I have created api keys; lets say "apikey1", "apikey2" and "apikey3". I can grant permissions for urls "a" and "b" and then "c" wont be accesible by any apikey; but all the apikeys can access all registered urls (or views). What I need is to restrict "apikey1" to only "a/" "apikey2" only to "c/" and "apikey3" access to both. I know I can do it with users by checking authenticated user in the request and then verify aganinst some list; if the user is in my list, keep going, else redirect 400 or whatever. but how do I do that with apikeys? -
Creating printable forms with Python and Django backend
I want to create a Saas website (for our company's internal use, but I don't see why it couldn't be a full service down the line. The service will provide an way for users to create forms for our industry, and there are a lot of legislated forms. Those forms should be able to be exported to PDF to be added to a different client management software as attachments. I am building it with Django/Python/MySQL backend and HTML, CSS, Javascript frontend. My question is this: What would be the best way to produce well-formatted print/PDF forms. My current ideas are: Using pre-designed PDF interactive PDF forms and have the system insert values into the PDF form fields Using the same idea, but with a Word document (although I don't much favour this Ideally, I would like to be able to form the document fully in the backend, but I haven't really found out how to do this. Any ideas would be greatly appreciated - thank you! -
How to subtract from a Django model?
I am trying to add and subtract 1 from the value of a Django model's IntegerField and display it on the webpage, depending on when a button is clicked. models.py class User(AbstractUser): following = models.ManyToManyField("self", related_name="followers", symmetrical=False) following_num = models.IntegerField(default=0) In views.py: To add: following_num = F('User.following_num') + 1 To subtract: following_num = F('User.following_num') - 1 This is displaying in the html where the number should be displaying: <django.db.models.query_utils.DeferredAttribute object at 0x0000022868D735E0> -
add form field or model from sibling model to django-admin page
I want to add form fields on django admin panel from related siblings. my models: class Post(models.Model): messageContent= models.TextField(null=True, blank=True) subject= models.ForeignKey('posts.Subject', on_delete=models.PROTECT, related_name='posts') class Subject(models.Model): name = models.CharField(max_length=15) class SubSubject(models.Model): name = models.CharField(max_length=15) threatment=models.ForeignKey('posts.Subject', on_delete=models.CASCADE, related_name='sub_subject') I want to add sub_subject model or sub_subject.name field to order admin page, and it is better if when I select Subject, only related sub_subjects seen on select menu. I am a beginner so anyone can help me? -
Is it possible to convert these FBVs that return HttpResponse() into CBVs? (Django)
I currently have the following function-based views, their purpose is to take a specific action based on what the user selected: @login_required() @csrf_exempt def remove_member(request, pk, project_id): if request.method == 'POST': user = get_object_or_404(User, id=pk) project = get_object_or_404(Project, id=project_id) project.members.remove(user) html = '<div class="alert alert-success" role="alert" id="message-response">' \ 'Update successful! ' + user.first_name + ' is no longer part of your team. </div>' return HttpResponse(html) @login_required() @csrf_exempt def demote_admin(request, pk, project_id): if request.method == 'POST': user = get_object_or_404(User, id=pk) project = get_object_or_404(Project, id=project_id) project.admin.remove(user) html = '<div class="alert alert-success" role="alert" id="message-response">' \ 'Update successful! ' + user.first_name + ' is no longer an admin. </div>' return HttpResponse(html) I'm using htmx on the template to populate a div with the returned html. There are several similar functions to the examples above. So I would like to convert these into a single CBV in order to reduce redundancy. The new CBV would also require some sort of check, in order to take the appropriate action. However, I'm not sure which class would be best suited for this, and which method would be best to override in this scenario. (admin and members are M2M fields assigned to the Project model) -
Error: Django model form data not being saved in the database
I'm trying to create a blog model but the form data is not being saved in the database after submitting the form. views.py def postsform(request): if request.method == "POST": form = BlogForm(request.POST) if form.is_valid(): form.save() return redirect('blog') else: form = BlogForm() messages.warning(request, "Opps! Something went wrong.") return render(request, 'blog/postform.html', {'form':form}) else: form = BlogForm() return render(request, 'blog/postform.html', {'form':form}) forms.py from django_summernote.widgets import SummernoteWidget class BlogForm(ModelForm): class Meta: model = BlogPost widgets = { 'blog': SummernoteWidget(), } fields = ['title', 'featureImg', 'blog', 'meta_description', 'keyword', 'author'] models.py class BlogPost(models.Model): title = models.CharField(max_length=999) featureImg = ProcessedImageField(upload_to = 'blog/', format='JPEG',options={'quality':60}, null=True) slug = models.CharField(max_length=999, blank=True,null= True) blog = models.TextField() meta_description = models.TextField() keyword = models.TextField() author = models.CharField(max_length=255) created_on = models.DateField(auto_now_add=True) updated_on = models.DateField(auto_now=True) def save(self, *args, **kwargs): if BlogPost.objects.filter(title=self.title).exists(): extra = str(randint(1, 1000000)) self.slug = slugify(self.title) + "-" + extra else: self.slug = slugify(self.title) super(BlogPost, self).save(*args, **kwargs) html <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Publish</button> </form> I've tried finding where I made the mistake but couldn't find it. After submitting the form the warning message pops up and the form doesn't get submitted. -
Django: Forloop Counter 0 divisible by 3 not working properly
PLATFORM: Django Problem When using {% forloop.counter0|divisibleby:3 %} it doesn't seem to properly divide out? I can't quite tell what's going on. Goal Display an Avery HTML template with pre-populated info from the database. 3 column table with variable rows. Code <table> {% for job in jobsite %} {% if forloop.counter0|divisibleby:3 %}<tr>{% endif %} <td>{{ job.name }}<br/>{{ job.address }}<br/>{{ job.address_2 }}{% if job.address_2 %}<br/>{% endif %}{{ job.city }}, {{ job.state }} {{ job.zip }}</td> {% if forloop.counter < 3 %} <td class="spacer" rowspan="0">&nbsp;</td> {% endif %} {% if forloop.counter0|divisibleby:3 or forloop.last %}<tr>{% endif %} {% endfor %} </table> Why is this failing? Additional Info I can get close if I change the code around to the following. The problem then becomes that counter 2 is blank. If I fill in data, it's duplicated (row 1 column 2, row 1 column 3): <table> <tr> {% for job in jobsite %} {% if forloop.counter|divisibleby:3 %}</tr><tr>{% endif %} <td>{{ job.name }}<br/>{{ job.address }}<br/>{{ job.address_2 }}{% if job.address_2 %}<br/>{% endif %}{{ job.city }}, {{ job.state }} {{ job.zip }}</td> {% if forloop.counter < 3 %} <td class="spacer" rowspan="0">&nbsp;</td> {% endif %} {% if forloop.counter == 2 %} <td></td> {# <td>{{ job.name }}<br/>{{ job.address }}<br/>{{ … -
How to count the number of specific objects in a Django model?
I have a Django model called User and would like to count how many items are within the following object. class User(AbstractUser): following = models.ManyToManyField("self", related_name="followers") I have tried counting them using this line followers_num = User.following.count(), but I receive this error 'ManyToManyDescriptor' object has no attribute 'count'. I have also tried followers_num = User.objects.all().count(), but that returns the number of users. Does anyone know how to do this? -
How would I use write a test case to login using the email
In the functions test_login and test_get_add_page I would like to login using the email,pw and then for one to redirect to the add page and check if it's using the right template. Running the following gives me: Traceback (most recent call last): File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\utils\datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'username' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\instawork\Internship\tests.py", line 89, in test_login user_login = self.client.post(self.login_url, {'email': self.user.email, 'password': self.user.password}) File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\test\client.py", line 852, in post response = super().post( File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\test\client.py", line 44 return self.generic( File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\test\client.py", line 541, in generic return self.request(**r) File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\test\client.py", line 810, in request self.check_exception(response) File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\test\client.py", line 663, in check_exception raise exc_value File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\instawork\Internship\views.py", line 21, in login username = request.POST['username'] File "C:\Users\arund\Desktop\Code\Instawork-Fall-Internship-2022\env\lib\site-packages\django\utils\datastructures.py", line 86, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'username' I am trying to use email instead of the username for my default login. from django.test import TestCase, Client from django.urls import reverse from .models import Profile, Team from .forms import ProfileForm # Create your tests here. class Instawork(TestCase): #fields are first_name, last_name, … -
How to use media files on heroku?
There is a way to use media files on heroku? if yes, how I have to set MEDIA_URL and MEDIA_ROOT? -
How would I get sum from all rows, but only output one row? Django and Postgresql
currently the way I have the code written is that I have a model named Finances. I have an aggregate set up so it sums up all of the rows. I am trying to display the outcome of the rows, but when I do it displays a row for every database entry. I understand that I am grabbing all with .all() in the viewpayout = Finances.objects.all() in views.py, but I am unsure of how this should be written to only display one row. How would I display only one row that sums up all of the rows for a column? Any help is greatly appreciated! Below is my code: views.py def finances(request): viewpayout = Finances.objects.all() updatepayout = UpdatePayout() updatewithdraw = UpdateWithdraw() updatecash = UpdateCash() if request.method == "POST": if 'add_payout' in request.POST: updatepayout = UpdatePayout(request.POST) if updatepayout.is_valid(): post = updatepayout.save(commit=False) post.save() return redirect("/finances") else: updatepayout = None if 'bank_withdraw' in request.POST: updatewithdraw = UpdateWithdraw(request.POST) if updatewithdraw.is_valid(): post = updatewithdraw.save(commit=False) post.save() return redirect("/finances") else: updatewithdraw = None if 'add_cash' in request.POST: updatecash = UpdateCash(request.POST) if updatecash.is_valid(): post = updatecash.save(commit=False) post.save() return redirect("/finances") else: updatecash = None return render(request, 'portal/finances.html', {"updatepayout": updatepayout, "updatewithdraw": updatewithdraw, "updatecash": updatecash, "viewpayout": viewpayout}) model.py: class Finances(models.Model): payout … -
CustomUser in Django with failed migration
I did migration in Django for my database. My models.py file looks like this from django.contrib.auth.models import AbstractUser from django.db import models from tkinter import CASCADE from django.dispatch import receiver from django.db.models.signals import post_save # Create your models here. class CustomUser(AbstractUser): user_type_data = ((1,"Manager"),(2,"Employee")) user_type = models.CharField(default = 'test', choices = user_type_data, max_length=20) class Manager(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length = 100,default='test') email = models.CharField(max_length = 100,default='test') password = models.CharField(max_length = 100,default='test') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now_add = True) objects = models.Manager() class Tasks(models.Model): id = models.AutoField(primary_key=True) headline = models.CharField(max_length = 100) body = models.CharField(max_length = 10000) created_at = models.DateTimeField(auto_now_add = True) assigned_at = models.DateTimeField(auto_now_add = True) closed_at = models.DateTimeField(auto_now_add = True) manager_id = models.ForeignKey(Manager, on_delete=models.CASCADE) objects = models.Manager() class Employee(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length = 100,default='test') email = models.CharField(max_length = 100,default='test') password = models.CharField(max_length = 100,default='test') objects = models.Manager() created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now_add = True) tasks_id = models.ForeignKey(Tasks, on_delete=models.CASCADE) daily_r = models.IntegerField(default = 0) weekly_r = models.IntegerField(default = 0) monthly_r = models.IntegerField(default = 0) annual_r = models.IntegerField(default = 0) Sometimes it says "Table does not exist", but after I change something … -
Conversion from Markdown to HTML in Django project
I'm on a project which include use of Python, Django, HTML and Markdown. I have to develop a site similar to wikipedia, in fact the project is called encyclopedia. My goal is to make visiting / wiki / TITLE, where TITLE is the title of an encyclopedia entry, to display a page that displays the content of that encyclopedia entry. The encyclopedia entries are CSS Django Git HTML Python (each entry has its own .md file). the problem I have is with the "markdown" library. In practice, I was able to convert the syntax from markdown to HTML but as output I only receive the tags in written format, without them applying their standard style to the content inside them. I am attaching the code I wrote for the conversion and a screenshot of the output I receive. from django.shortcuts import render import markdown from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, title): content = util.get_entry(title) if content == None: content = markdown.markdown(f'## {title.capitalize()}\'s page has not been found') content = markdown.markdown(content) return render(request, f"encyclopedia/entry.html", { 'title': title, 'content': content }) -
How Can I do PIN Activation, user registration and Authentication in Django
I am working on a Django project where users would have to activate PIN and then register for an event seat. I have done it in such a way that users activate PIN and they are prompted with registration form to secure a seat for an event. And I want to get the Event name, Price, Date, category from the Ticket table. Meanwhile I have a Guest Model that is saving username and pin using an update query during the registration process; using a forms field to request for PIN again (Don't want to repeat this process too). And I have used the pin field as a ForeignKey in the Guest Model so I am getting error that Cannot assign "'384513'": "Guest.pin" must be a "Pin" instance. What is the best way of doing this logic of PIN activation, registration and authenticating a user and getting the Models values associated with his PIN in this case. I was thinking of using the Guest Table to get the information relating to Events, Ticket and Pin Details but no way. See below Models code: class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) price = models.PositiveIntegerField() category = models.CharField(max_length=100, choices=PAYMENT, default=None, blank=False, null=False) added_date = …