Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set hourly limit on DateTimeField Django
class Event(models.Model): start = models.DateTimeField(default=timezone.now) end = models.DateTimeField() How can I set hard limit for setting end_date? So if the user wants to set anything over 5hours from start system won't let him do that -
The specified start time of the periodic task is ignored
I am trying to specify the time at which a periodic task created using the django-celery-beat application should be run, thus: # Incomplete project structure ├── config │ ├── asgi.py │ ├── celery.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── order_monitoring │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── models.py │ ├── tasks.py │ ├── tests.py │ ├── urls.py │ ├── utils │ │ ├── scraperr │ │ │ ├── browser.py │ │ │ ├── chromedriver │ │ │ ├── db_scraper │ │ │ └── scraper.py │ │ └── utils.py │ └── views.py # config/settings.py ... USE_TZ = True TIME_ZONE = 'Europe/London' REDIS_HOST = '127.0.0.1' REDIS_PORT = '6379' CELERY_BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} CELERY_RESULT_BACKEND = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_IGNORE_RESULT = False CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_ENABLE_UTC = False CELERY_TIMEZONE = TIME_ZONE # config/celery.py import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') app = Celery('config',) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() # order_monitoring/utils/utils.py ... timezone = pytz.timezone('Europe/London') schedule, _ = CrontabSchedule.objects.get_or_create( minute='1', hour='*', day_of_week='*', day_of_month='*', month_of_year='*', timezone=timezone, ) … -
Django simpleJWT error "detail": "No active account found with the given credentials"
i'm trying to log into an account that isn't superuser and getting an error from rest_framework "detail": "No active account found with the given credentials" using a custom user model models.py : lass UserAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError('Users must have an email') email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name) user.set_password(password) user.save() return user class CustomUser(AbstractBaseUser, PermissionsMixin ): first_name = models.CharField(unique=True, max_length=200) last_name = models.CharField(unique=True, max_length=200) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.CharField(unique=True, max_length=200) username = models.CharField(unique=True, max_length=200) email = models.EmailField(unique=True) User_Roles = models.ForeignKey(User_Roles, on_delete=models.CASCADE) USERNAME_FIELD = 'username' objects = BaseUserManager() i checked that the passwords are being hashed in the db but does not seem to be the case serializers.py : class RegisterSerializer(ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}) class Meta(): model = CustomUser fields = ['username', 'email', 'first_name', 'last_name', 'password', 'password2'] def save(self): user = CustomUser( email=self.validated_data['email'], username=self.validated_data['username'], first_name=self.validated_data['first_name'], last_name=self.validated_data['last_name'], ) password = self.validated_data['password'], password2 = self.validated_data['password2'], if password != password2: raise serializers.ValidationError({'password': 'Passwords must Match'}) user.set_password(str(password)) user.save() return user i had error where the password type was a tuple rather than a string or byte, and user.set_password(str(password)) seems to have fixed the issue that i wasn't able to figure out, … -
header not visible in django page
I am trying to render a page with header but header is not being rendered. content of categories.html is displaying perfectly. I have added header block on index.html page.What am i doing wrong here? index.html {% load static %} <link rel="icon" href="{% static 'stocks/logo.png' %}"> <html> <body> <div> {% block header %} {% endblock %} </div> {% block stocks_page %} {% endblock %} </div> </body> </html> header.html {% extends "stocks/index.html" %} {% block header %} <h1>Header content goes here</h1> {% endblock %} categories.html {% extends "stocks/index.html" %} {% load static %} {% block stocks_page %} <link rel="stylesheet" type="text/css" href="{% static 'stocks/style.css' %}"> {% if categories %} <h2>Product categories</h2> <table> <tr> <th>Name</th> <th>Count</th> </tr> {% for each in categories %} <tr> <td>{{ each.name }}</td> <td>{{ each.count }}</td> </tr> {% endfor %} </table> {% endif %} <form action="/stocks/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} views.py def product_categories(request): ---------------------- < code > ---------------------- return render(request, 'stocks/categories.html') -
DJANGO WSGI: ModuleNotFound when deploying as monorepo
I am trying to deploy a dockerized django app to digitalocean. It passes the build section, but shows the following error in deploying section: No module named 'backend-server'. 'backend-server' is the name of the directory that has all the backend files in my monorepo. From the error log, I'm assuming there's a problem with my wsgi settings, but I cannot find where to start looking. [2022-07-30 14:35:47] [2022-07-30 14:35:47 +0000] [2] [INFO] Starting gunicorn 20.1.0 [2022-07-30 14:35:47] [2022-07-30 14:35:47 +0000] [2] [INFO] Listening at: http://127.0.0.1:8000 (2) [2022-07-30 14:35:47] [2022-07-30 14:35:47 +0000] [2] [INFO] Using worker: sync [2022-07-30 14:35:47] [2022-07-30 14:35:47 +0000] [4] [INFO] Booting worker with pid: 4 [2022-07-30 14:35:47] [2022-07-30 14:35:47 +0000] [4] [ERROR] Exception in worker process [2022-07-30 14:35:47] Traceback (most recent call last): [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker [2022-07-30 14:35:47] worker.init_process() [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process [2022-07-30 14:35:47] self.load_wsgi() [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi [2022-07-30 14:35:47] self.wsgi = self.app.wsgi() [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi [2022-07-30 14:35:47] self.callable = self.load() [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load [2022-07-30 14:35:47] return self.load_wsgiapp() [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp [2022-07-30 14:35:47] return util.import_app(self.app_uri) [2022-07-30 14:35:47] … -
Django: get_context_data for comments related post
I have a models: class Post(models.Model): post_text = models.CharField(max_length=100, unique=True) slug = models.SlugField(unique=True) created_at = models.DateTimeField(auto_now_add=True) class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') post_relation = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='comments') comment_text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) In my views I need get comments for posts in get_context_data: class ResultsView(DetailView, FormMixin): model = Post template_name = 'posts.html' form_class = CommentForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comm'] = Comment.objects.filter(is_active=True) return context But in comm i get all comments in db. In html: {% for comment in question.comments.all %} <div class="media mb-4"> <div class="media-body"> <h5 class="mt-0">{{ comment.author }}</h5> {{ comment.comment_text }} </div> </div> {% endfor %} I try {% for comment in comm %}, try {% for comment in comm.all %} and always get all comments in db, not only comments in post. Also I try fix this string in views: context['comm'] = Comment.objects.filter(is_active=True), but don't have a result. The answer seems to be very simple, but I've already spent several hours trying and reading. Any help is welcome. -
Why does my Django test pass when it should fail?
I am new to testing of any sorts in coding. This is followup on this answer to my question. Answer establishes that this type of model method should not save object to database: @classmethod def create(cls, user, name): list = cls(user=user, name=name) return list If this is the case I am curious why does this test pass and says everything is ok? from django.test import TestCase from .models import List from django.contrib.auth.models import User class ListTestCase(TestCase): def setUp(self): user_1 = User(username="test_user", password="abcd") user_1.save() List.objects.create(user=user_1, name="mylist") List.objects.create(user=user_1, name="anotherlist") def test_lists_is_created(self): user_1 = User.objects.get(username="test_user") list_1 = List.objects.get(user=user_1, name="mylist") self.assertEqual("mylist", list_1.name) -
What is the problem named, 'img' attribute has no file associated with it.?
My motive is to show the product_image in the orderlist template. The ProductOrder works well and it also stores the product_image url in the img in the database. But when tried to show the image in the template, it has shown an error. Where did the actual problem occur? Please give me a relevant solution. 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_image = models.ImageField(blank=True, null=True, upload_to = "1_products_img") class ProductOrder(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='UserOrderRelatedName',on_delete=models.CASCADE) img = models.ImageField(blank=True, null=True) views.py: this works well, def Order(request, quick_view_id): OrderProduct = get_object_or_404(Products, pk=quick_view_id) if request.method == "POST" and request.user.is_authenticated: ProductOrder.objects.create( img = OrderProduct.product_image ) return redirect('quick_view', quick_view_id) def OrderList(request): AllOrder = ProductOrder.objects.all() context = { "AllOrder":AllOrder, } return render(request, "order_list.html", context) template: {% for order in AllOrder %} <img style="width: 100px;" src="{{order.img.url}}"> {% endfor %} error: ValueError at /OrderList/ The 'img' attribute has no file associated with it. Request Method: GET Request URL: http://127.0.0.1:8000/OrderList/ Django Version: 4.0.4 Exception Type: ValueError Exception Value: The 'img' attribute has no file associated with it. Exception Location: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\django\db\models\fields\files.py, line 40, in _require_file Python Executable: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site\\env', … -
Login Authentication with simplejwt in Django Rest Framework with templates and ajax
I am trying to make an application with Django Rest Framework and template without using any front-end application. I created the login form and user list by following this documentation https://www.django-rest-framework.org/topics/html-and-forms/. It works fine when submitting forms and showing list with templates. But when I am trying to authenticate login with simplejwt from the browser, the authentication fails. Failed Authentication Then I looked around and found this documentation https://ilovedjango.com/django/rest-api-framework/authentication/tips/working-example-of-jwt-authentication-with-ajax-django-rest-framework/ . I can use the ajax post call to get the token and set it to local storage on submit and set the header of another API later from the local storage, but in that case, it is not going to the action="{% url 'user:user-list-list' %}" of the form in the template after submit. So it stays on the login page and hits only the token/ URL for the token. When I add location.href = "{% url 'user:user-list-list' %}" in the ajax success, it loads the user_list but says 401 unauthorized. Here is my user_login.html template: {% load rest_framework %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <h1>User Login</h1> <form action="{% url 'user:user-list-list' %}" method="POST" id="login"> {% csrf_token %} <div class="form-group "> <label>Username</label> <input id="username" name="username" … -
how can i put a search box in my django app?
my code trying to make a search box for searching books is here, im trying to make a search box, when user enters the name of a book , like google, it be shown on page , when i add {{form}} to book.html file it has to shows a box, but it doesnt , views.py: def books(request): if request.method == 'POST': form = DashboardFom(request.POST) text = request.POST['text'] url = 'https://www.googleapis.com/books/v1/volumes?q='+text r = requests.get(url) answer = r.json() result_list = [] for i in range(10): result_dict = { 'title':answer['items'][i]['volumeInfo']['title'], 'subtitle':answer['items'][i]['volumeInfo'].get('subtitle'), 'description':answer['items'][i]['volumeInfo'].get('description'), 'count':answer['items'][i]['volumeInfo'].get('pageCount'), 'catagories':answer['items'][i]['volumeInfo'].get('catagories'), 'rating':answer['items'][i]['volumeInfo'].get('pageRating'), 'thumbnail':answer['items'] [i]['volumeInfo'].get('imageLinks').get('thumbnail'), 'preview':answer['items'][i]['volumeInfo'].get('previewLink') } result_list.append(result_dict) context={ 'form':form, 'result':result_list, } return render(request,'dashboard/books.html',context) else: form = DashboardFom() context = {'form':form} return render(request,'dashboard/books.html',context) forms.py: class DashboardFom(forms.Form): text = forms.CharField(max_length=100,label='Enter your search : ') and also my books.html: {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <section class='text-center container'> <h2>Search books and browse your favorite</h2> <p>just enter the search query to obtain the results</p><b></b> <form action="" method="POST"> {% csrf_token %} {{form}} <input class="btn btn-danger" type="submit" value="Submit"> </form><br> {% for result in results %} <a href="{{result.preview}}" target="_blank"> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-3"> <img class="img-fluid" src="{{result.thumbnail}}" alt=""> </div> <div class="col-md-9"> <h3 class="p-0 m-0">{{result.title}}</h3> <b> <u> <h5 class="p-0 … -
How do I rename app on Github marketplace
I have a marketplace app https://github.com/marketplace/django-doctor/ (For context it offers fixes to Python and Django mistakes right inside the Github PR). but since creating the marketplace app I renamed the product to Code Review Doctor (it used to only offer fixes to Django code, but expanded to Python too and so the name had to change oops) I cannot see any way to rename the app and the link. Is this achievable some other way? I can't find a way to contact GitHub customer support. -
Why am I getting an error that my model form object has no attribute 'cleaned_data'?
I have a form on a page that users use to write comments. There is a view (comment) that should take in the users inputs along with some other information and save it to a model. However, when I tested it out, I got the error: 'CommentForm' object has no attribute 'cleaned_data' How do I fix this? views.py: def comment(request, id): if request.method == 'POST': form = CommentForm(request.POST) # the form if form.is_valid: current = get_object_or_404(Listing, id=id) user = User.objects.get(pk=request.user.id) obj = Comment() # the model obj.user = user obj.listing = current obj.date = datetime.datetime.now() obj.title = form.cleaned_data['title'] # this is where the error occurs obj.comment = form.cleaned_data['comment'] obj.rating = form.cleaned_data['rating'] obj.save() return listing(request, current.id, current.name) html: <form action=" {% url 'comment' listing.id %} " method="post" class="comment-form"> {% csrf_token %} <h2>Comment</h2> {{ commentForm.title }} {{ commentForm.comment }} {{ commentForm.rating }} <input type="submit" value="Comment" class="submit-btn"> </form> forms.py: class CommentForm(forms.Form): title = forms.CharField(max_length=60, widget=forms.TextInput(attrs={ 'class': 'comment-title', 'placeholder': 'Title', })) comment = forms.CharField(max_length=1000, widget=forms.Textarea(attrs={ 'class': 'comment', 'placeholder': 'Enter Comment' })) rating = forms.FloatField(min_value=0, max_value=5, widget=forms.NumberInput(attrs={ 'class': 'rating', 'placeholder': 'Rating' })) -
Django - Prevent admin command to run twice
My problem is simple, i have an admin command name "send email": The problem is, the admin user succeed to call this function twice in a row. Probably in click on "Go" many time. So it sent email many time. There is a way to prevent it ? I tried to put a timeout in the end of the admin function "send_email" but it's not good ... It take 10 second between each users, and i have lot of users. def send_email(modeladmin, request, queryset): ... time.sleep(10) -
Does create() method save model object to Django database?
I just came across using create methods in Djangos models.Model subclass. Documentation has this example code: from django.db import models class Book(models.Model): title = models.CharField(max_length=100) @classmethod def create(cls, title): book = cls(title=title) # do something with the book return book book = Book.create("Pride and Prejudice") Does this already save new Book object to database? My intuition suggests that save() method should be called on the line # do something with the book or else it should not work. However when I try testing it, it seems that addin save() to it does not affect anything what so ever. Why is that the case and how does it actually save object to database? PS. I came across this while trying to learn testing with TestCase. If classmethod does not save anything to database problem is probably my testing code, but that would be whole another question. -
I am working on django project through github in which i get this error even after import or install all requirements
raise ImproperlyConfigured(error_msg) from exc django.core.exceptions.ImproperlyConfigured: Set the DB_NAME environment variable -
VSCode testing uses production database instead of test database
In VSCode testing, the real production database is used. What should happen is Company.objects.create(name='kfc') creates a single Queue object for that associated Company (shown in models.py if interested) for a test database that's created for this test, then the test database gets destroyed at the end of the test. Instead, VSCode uses my production database, which does include a mcdonald's queue. Because my view uses the pk to determine the queue, and since mcdonald's queue is present, it gets the wrong queue and the test fails. However, when I try to run the tests manually, python manage.py test api.tests, the test passes since I think django's test themselves do use test databases. models.py class Company(models.Model): name = models.CharField(max_length=15) def save(self, *args, **kwargs) -> None: created = bool(self.pk) super().save(*args, **kwargs) if not created: Queue.objects.create(company=self) class Queue(models.Model): company = models.OneToOneField( Company, on_delete=models.CASCADE, related_name="queue") users = models.ManyToManyField(User, through="QueueDetails") @property def length(self): return len(self.users.all()) @property def sorted_users(self): return self.users.all().order_by("queue_details__joined_at") def __str__(self) -> str: return f"{self.company}'s queue" Please let me know if I'm missing something and how to make VSCode work with Django tests, thanks. -
webpack_loader.exceptions.WebpackBundleLookupError: Cannot resolve bundle vendor. on webpack loader
I start the server for webpack. The log is here below. yarn dev yarn run v1.22.18 warning ../package.json: No license field warning ../../package.json: No license field $ webpack-dev-server --mode=development <i> [webpack-dev-server] Project is running at: <i> [webpack-dev-server] Loopback: http://localhost:3000/ <i> [webpack-dev-server] On Your Network (IPv4): http://10.41.232.84:3000/ <i> [webpack-dev-server] On Your Network (IPv6): http://[fe80::1]:3000/ <i> [webpack-dev-server] Content not from webpack is served from '/Users/whitebear/MyCode/httproot/aicomposer_cdk/aicomposer/frontend/public' directory (node:50012) [DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH] DeprecationWarning: [hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details) (Use `node --trace-deprecation ...` to show where the warning was created) asset js/vendor.911d558c052970cd108d.bundle.js 210 KiB [emitted] [immutable] (name: vendor) (id hint: commons) asset js/base.911d558c052970cd108d.bundle.js 54 KiB [emitted] [immutable] (name: base) Entrypoint base 264 KiB = js/vendor.911d558c052970cd108d.bundle.js 210 KiB js/base.911d558c052970cd108d.bundle.js 54 KiB runtime modules 28.3 KiB 13 modules modules by path ./node_modules/ 166 KiB modules by path ./node_modules/webpack-dev-server/client/ 53.5 KiB 12 modules modules by path ./node_modules/style-loader/dist/runtime/*.js 5.75 KiB 6 modules modules by path ./node_modules/webpack/hot/*.js 4.3 KiB 4 modules modules by path ./node_modules/html-entities/lib/*.js 81.3 KiB 4 modules modules by path ./node_modules/css-loader/dist/runtime/*.js 2.33 KiB ./node_modules/css-loader/dist/runtime/noSourceMaps.js 64 bytes [built] [code generated] ./node_modules/css-loader/dist/runtime/api.js 2.26 KiB [built] [code generated] ./node_modules/ansi-html-community/index.js 4.16 KiB [built] [code generated] ./node_modules/events/events.js 14.5 KiB [built] [code generated] modules by path ./static/ … -
Why despite no error, the List View does not work?
I am not getting any error but my list view does not function. The detail view at the top with ID =1 is working fine. I change the ID numbers and can see the different posts. But when I go to the URL http://127.0.0.1:8000/feed/, the detail view remains stuck whereas I should be seeing 3 posts vertically. It is almost as if the page is not refreshing, Perhaps class-based views are better ways to do it, but for my own learning I want to know why this is not working. def feed_detail_view(request, id = 1): obj = Feed.objects.get(id=id) #print(obj) context = { "object" : obj, } return render(request, 'feeds/detail_view.html',context) def feed_list_view(request): queryset = Feed.objects.all() context = { "object_list" : queryset } return render(request, 'feeds/list_view.html',context) #code in my list_view html {% for object in object_list %} {{object.content}} <br/> {{object.user}} <br/> {{object.timestamp|timesince}} {{% endfor %}} -
What does django urlpattern path argument empty (' ') meaning?
what does path('') in urls.py from project mean? This is urls.py from project. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')) ] And this is urls.py from app urlpatterns = [ path('', views.index), path('create/', views.create), path('read/id/', views.read), ] Is path('')in urls.py from project just mean empty? If it is, why when I write localhost:8080/create It will still work? I just routing path('') in urls.py from project Does it mean "except admin/" ..? -
Django DRF: how to groupby on a foreign fields?
I have a model where users can upvote other users for specific topics. Something like: #models.py Class Topic(models.Model): name = models.StringField() def __str__(self): return str(self.name) Class UserUpvotes(models.Model): """Holds total upvotes by user and topic""" user = models.ForeignKey(User) topic= models.ForeignKey(Topic) upvotes = models.PositiveIntegerField(default=0) Using DRF, I have an API that returns the following: topic_id, topic_name, and upvotes, which is the total upvotes for a given topic. One of the project requirements is for the API to use these field names specifically: topic_id, topic_name, and upvotes #serializers.py class TopicUpvotesSerializer(serializers.ModelSerializer): topic_name = serializers.StringRelatedField(source="topic") class Meta: model = UserUpvotes fields = ["topic_id", "topic_name", "upvotes"] My trouble is aggregating these fields. I'm filtering the UserUpvotes by user or team and then aggregating by topic. Desired output This is the result I want to get. When I don't perform any aggregations (and there are views where this will be the case), it works. [ { "topic_name": 3, "topic_name": "Korean Studies", "upvotes": 14 }, { "topic_name": 12, "topic_name": "Inflation", "upvotes": 3 }, ] At first, I tried creating a TopicSerializer, and then assigning it to the topic field in TopicUpvotesSerializer. But then, the resulting json would have a nested "topic" field and the aggragation would fail. Attempt … -
Which one is the correct way of using Python type hints with Django Models?
Which one of these is the correct way to use type annotations for django models? from typing import TypeVar, Generic from app.models import MyModel _T = TypeVar("_T", bound=MyModel) def func(arg: Generic[_T]): ... Or from typing import Type from app.models import MyModel def func(arg: Type(MyModel)): ... Or from app.models import MyModel def func(arg: MyModel): ... -
Javscript: Click event not working as expected?
i am trying to build an ecommerve platform using django and javascript, i have built the django server side, which when i call {{ product.id }} in my template, it should show the id for each product, now i want to get each id when i click on a button but nothing is showing up in the console. This is how the template looks index.html {% for product in products %} <p>{{ product.title }}</p> <button data-product="{{product.id}}" data-action="add" class="update-cart">Add to Cart</button> {% endfor %} now the javascript looks like this cart.js var updateBtns = document.getElementsByClassName('update-cart') console.log("Working"); for (i = 0; i > updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId is:', productId, 'Action is:', action) console.log('USER:', user) }) } this console.log('productId is:', productId, 'Action is:', action) and console.log('USER:', user) does not work. What could i be missing? -
How can I select property method of a django model in sqlalchemy
I have two models named student and payment. The relation is a student has many payment. Their codes are like Class Student(Model): id: IntegerField() name: CharField() payment = relation('Payment') @property get_total_payment(self): //calculate total payment Class Payment(Model): id: IntegerField() amount: IntegerField() student_id: ForeignKey() Now I have written a query like this. select = [ Student.id, Student.name, Markshit.number, Markshit.subject_name, ] query = sa_session.query(*select).join(Markshit).all() I want to add Student.get_total_payment in the query but gets error. How can I solve this? -
Web app security: Sending cookie along with JWT (django rest framework)
I have an Angular web app which works in conjunction with a Django Rest Framework backend. Authentication is done by means of JWT tokens. However, for some management actions, users need to go to the Django admin page. Since the Django admin page works with Cookies instead of JWTs, the user needs to log in again. A minor nuisance, but a nuisance all the same. The question is whether it makes sense to extend the Rest Framework's authentication methods to set a session cookie when the user first receives their JWT? Or would it be better to ditch JWT altogether and use cookies for the web app as well? -
How to order by based on serializer fields in django?
Here I am ordering my response list data based on the obtained value from SerializerMethodField but while doing on this approach my api responding very slowly like 14-15s but without using this sorting and using only queryset the response time is like 12-1300ms so How can I optimize this code ? I think using queryset.order_by would be faster rather than sorting from list but How can I use order_by here since I need to order by the serializermethodfield value. # serializer class MySerializer(serializers.ModelSerializer): duration = serializers.SerializerMethodField() def get_duration(self, obj): dt1 = obj.files.filter(type="1").first().approved_on dt2 = timezone.now() days = (dt2-dt1).days return days # views @api_view("GET"): def get_list_of_items(self, request): user = request.user limit = int(request.GET.get('limit', 30)) offset = int(request.GET.get('off', 0)) max = limit + offset qs = MyModel.objects.filter(user=user, status="DONE").prefetch_related("files") serializer = MySerializer(qs, many=True) sorted_ls = sorted(serializer.data, key=lambda k: k['duration'])[offset:max] return Response{'data':sorted_ls}