Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.IntegrityError when sending post request with axios in vue
im new to web development so please explain your solution i am trying to send data to an endpoint in the api i created with the django rest framework in vue with axios but whenever i do i get this error : django.db.utils.IntegrityError: NOT NULL constraint failed: main_checkbox.label (i know im not building the api the way its supposed to be built but thats another problem) i can make a get request with axios no problem and i can even send post data via an html form with no problem (but i dont want to cause im creating a single page application with vue and don't want it to refresh when submitting) here is the vue code : <template> <div class="home"> <input type="text" name="label" id="" v-model="label" /> <input type="submit" value="Create" @click="createCheckbox" /> </div> </template> <script> import axios from "axios"; export default { data() { return { label: "", }; }, methods: { async createCheckbox() { let result = axios.post("http://127.0.0.1:8000/create/", { label: this.label, }); console.log(result); }, }, }; </script> the django views code : from rest_framework.response import Response from rest_framework.decorators import api_view from main.models import checkbox from main.serializers import checkboxSerializer @api_view(['POST']) def create(request): checkboxobj = checkbox.objects.create( state=False, label=request.POST.get('label')) serialized = checkboxSerializer(checkboxobj) … -
Django forms not passing form.is_valid() condition
In my views.py my have a view where a user can create a post with a title, media file and caption. When i check if form.is_valid(): it always returns as false and i cannot see the issue with my form. views.py def your_profile(request): if request.method == "POST": form = CreatePost(request.POST) if form.is_valid(): title = form.cleaned_data.get("title_input") media = form.cleaned_data.get("media_input") caption = form.cleaned_data.get("caption_input") context = {"title": "Your Profile"} return render(request, "myApp/your_profile.html", context) forms.py class CreatePost(forms.Form): title = forms.CharField(max_length=30) media = forms.FileField(max_length=350) caption =forms.CharField(max_length=300) html <form action="" method="post"> <input type="text" name="title_input" id="title_input"> <label for="title_input">Title</label> <input type="file" name="media_input" id="media_input"> <label for="media_input">Media</label> <input type="text" name="caption_input" id="caption_input"> <label for="caption_input">Caption</label> <input type="submit" value="POST!"> </form> -
Why createsupersuer not loggin without any error in Django?
I have made super user like this: python manage.py createsuperuser username: something email: something password: something i checked the database and is_superuser=True is_staff=True is_active=True run my project: python manage.py runserver and call this address: http://127.0.0.1:8000/admin When enter username and password not loggin and not show any red message as error in the page. I don't know get error or redirect to the page. -
Django startserver/make migaration is picking wrong username rather than mentioned in settings.py file
I am new to django,i am facing issue like below,there is no soorya user in mysql database,but still it giving error when i try to do makemigrations and runserver.. Here is the output of mysql server database user select user,host from mysql.user output: mysql.infoschema localhost mysql.session localhost mysql.sys localhost rest localhost root localhost ======================= FYI. I had created a new mysql connection(soorya) by this name and deleted it as i was facing issue with django connection with mysql can any body help me on this. C:\Users\soorya\AppData\Local\Programs\Python\Python310\Lib\site-packages\django\core\management\commands\makemigrations.py:121: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (1045, "Access denied for user 'soorya'@'localhost' (using password: YES)") warnings.warn( No changes detected -
Django models normalization
having a simple ordinary model like this class Order(models.Model): open = models.DecimalField(max_digits=10, decimal_places=8) high = models.DecimalField(max_digits=10, decimal_places=8) low = models.DecimalField(max_digits=10, decimal_places=8) close = models.DecimalField(max_digits=10, decimal_places=8) time = models.DateTimeField() active = models.BooleanField(default=False) complete = models.BooleanField(default=False) works for my case but as there's only up to 1 active order at the same time, keeping it consistent is a challenge. don't wanna use transaction so the idea of separating active attribute would be a solution. I wondered if there's any better idea? for example, adding active as a database related attribute or something like a hook (believe me when I say I don't know if that's an option) -
How could I rework Django migrations without affecting database?
Basically I'm working on a project which already has a database managed with Django. I have noticed there are issues from the past. Duplicate migrations(eg.: 0011_auto_20210524_1314, 0011_auto_20210531_1728.), also there aren't all model fields recorded in migration history. The idea is that I would like to even split project into more apps than it is for now. So what I exactly would like to do is to go back to migration zero, delete all migrations and makemigrations again meanwhile models will be split into multiple apps. The issue is that database is containing a lot data and I can't affect them. Anyone have an idea how to reach it somehow "clean"? I've been thinking about --fake zero, delete migrations(Delete also from DB.), make new set of migrations, set flag managed = False and migrate so the migration would be "applied". I'm aware of inspectdb, but not sure if that would help due to moving models across multiple apps. Any other suggestions or thoughts please? -
How to make model for sub-category and category for product in django?
I have to make product model in django where when we select the the main category which is foreign key then we have to select sub category, problem is that it will show the all sub category. it have to show the sub category as per main category selected Main Category Model Here we just have three fields class Category(models.Model): image = models.ImageField(upload_to="maincategory",null=True) icon = models.CharField(max_length=200,null=True) title = models.CharField(max_length=200,null=True) def __str__(self): return self.title Sub Category Model here we give the Main category as foreignkey class SubCategory(models.Model): main_category = models.ForeignKey(Category,on_delete=models.CASCADE) title = models.CharField(max_length=200,null=True) def __str__(self): return self.main_category.title + " - " + self.title Product Model In The Product model i will give two foreign key for main and sub category maincategory = models.ForeignKey(Category,on_delete=models.CASCADE,null=True,blank=True) subcategory = models.ForeignKey(SubCategory,on_delete=models.CASCADE,null=True,blank=True) class Product(models.Model): sts = ( ("PUBLISH","PUBLISH"), ("DRAFT","DRAFT"), ) vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE) maincategory = models.ForeignKey(Category,on_delete=models.CASCADE,null=True,blank=True) subcategory = models.ForeignKey(SubCategory,on_delete=models.CASCADE,null=True,blank=True) title = models.CharField(max_length=200,null=True) description = models.TextField() price = models.IntegerField(null=True,default=0) discount = models.IntegerField(null=True,default=0) stock = models.IntegerField(null=True,default=0) size = models.CharField(max_length=200,null=True,blank=True) color = models.CharField(max_length=200,null=True,blank=True) date = models.DateTimeField(auto_now_add=True) slug = AutoSlugField(populate_from='title',unique=True,null=True,default=None) status = models.CharField(choices=sts,null=True) def __str__(self): return self.vendor + " - " + self.title So how to create model where select subcategory as per main category in admin panel django -
What model of raspberry pi good for local web server
Hello i need some useful information about running a local web server in a raspberry pi and the best embedded system that can handle my device what i mean? Well i've created a website using django + redis + celery + postgresql So what i want to do with this website is to Turn on/off LED lamp using a BreadBoard. this is done by celery ... actually there is a task (celery-beat-schedule) that should turn off/on some specific LED lamps and the django is the firmware that creates those tasks and controls my device For example: Imagine i have a task that represent the main job of the device (turning on/of) a i can create and run this tasks using django-celery-beat But The main question is how can i run this in a embedded system like raspberry pi. actually what are the best hardware like CPU RAM this website can run on that and does not crashed? For example, is Raspberry Pi zero w suitable for running this web server and setup? And there is no limit to the implementation? Of course, let me say this too. I don't want to spend too much otherwise I think the Raspberry Pi … -
Django - Consecutive Request Override Session Attribute
I want to generate an invoice for each order, and in some cases, there are two generated invoices for one order. For those cases, the first invoice request fails and I receive a 400 error with "invalid signature" message (as I defined in my view logic), while the second remaining success. My views.py from django.core import signing from django.contrib import messages class OrderView(MyMultiFormsView): forms = {‘create’: OrderForm} … # view logic for get method: display a list of orders def post(self, request, *args, **kwargs): form = self.forms[‘create’](request.POST, request.FILES, prefix=‘create’) if form.is_valid(): order = form.save() messages.success(request, signing.dump(order.id)) if order.is_paid: messages.info(request, signing.dump(order.id)) return redirect(request.get_full_path()) … # not valid: render form and show errors class ExportView(View): http_method_names = [‘get’] actions = { 'invoice': { 'url_token': 'print-invoice', 'session_prop': '_invoice_token', }, 'receipt': { 'url_token': 'print-receipt', 'session_prop': '_receipt_token', }, } def get(self, request, *args, **kwargs): if kwargs['action'] not in self.actions: return render(request, '400.html', {'msg': 'undefined action'}, status=400) action = self.actions[kwargs['action']] if kwargs['token'] == action['url_token']: try: token = request.session.pop(action['session_prop']) sign = signing.load(token) except: return render(request, '400.html', {'msg': 'invalid signature', status=400) return getattr(self, kwargs['action'])(sign) else: request.session[action['session_prop']] = kwargs['token'] print(request.session.__dict__) redirect_url = request.path.replace(kwargs['token'], action['url_token']) return redirect(redirect_url) def invoice(self, sign): inv = Invoice(sign) # inv.as_file() returns a pdf file with … -
Django: Problem with passing parameters from a template {% url %} to a view
I have this urlpath: path('download/<str:fpath>/<str:fname>', views.download, name='download'), And this is the view: def download(request, fpath, fname): # some code In template, I have this href tag and I want to pass those strings as arguments to the download view. <a href="{% url 'download' 'lms/static/lms/files/homework/Math 1/3/3' 'hmm.pdf' %}">click me</a> But I get this error: NoReverseMatch at / Reverse for 'download' with arguments '('lms/static/lms/files/homework/Math 1/3/3', 'hmm.pdf')' not found. 1 pattern(s) tried: ['download/(?P<fpath>[^/]+)/(?P<fname>[^/]+)\\Z'] How can I fix this? -
How do I return a 401 response in a SimpleJWT Custom Token when using the Django Rest Framework?
I would like to return a 401 message if the user is not enabled. When I try returning a response instead of a token it doesn't work which I understand to be because the serializer is expecting the token. How do I customise it to send a 401 response if the user is not enabled please? My custom token class is as below: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework import status from rest_framework.response import Response class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): if user.is_enabled: token = super().get_token(user) # Add custom claims token['name'] = user.name token['gender'] = user.gender return token else: return Response({'detail':'Account not enabled'}, status=status.HTTP_401_UNAUTHORIZED) class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer The URL root looks like: re_path(r'^authenticate/',CustomTokenObtainPairView.as_view(), name='authenticate'), -
NotSupportedError at / deterministic=True requires SQLite 3.8.3 or higher
I am trying to deploy a Django application using the default SQLite database to Elastic Beanstalk. The application works fine locally, however, on server, I get the error as : Any idea what's wrong? Can we not deploy SQLite app on AWS EBS? Here is my project structure that is getting deployed ├── .ebextensions │ ├── django.config ├── app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ ├── models.py │ ├── static │ │ └── app │ │ ├── app.js │ │ ├── logo.svg │ │ └── style.css │ ├── templates │ │ └── app │ │ ├── hello.html │ │ ├── index.html │ │ └── job_detail.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── env │ ├── All Virtual env related files ├── images │ ├── Photo_on_5-9-14_at_2.31_PM.jpg │ ├── Photo_on_5-9-14_at_2.32_PM.jpg │ └── Photo_on_5-9-14_at_2.32_PM_v4McLzE.jpg ├── myproject-test │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt ├── staticfiles │ |-- All static files collected using collectstatic │ ├── app │ │ ├── app.js │ │ ├── logo.svg │ │ └── style.css │ └── subscribe … -
Is there a way to pass a secret variable into a static JS File?
I have looked everywhere for a way to pass a secret variable into an API call that I make in a JS file on Django, but can't figure out a way. Is anyone familiar with this? -
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?