Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not redirecting to next page after login in Rest Framework
I have been trying to redirect the user to the main page after successful login in API. Email id and password which will be comes from the Angular. However, the email and password which is already existed in the SQL server where I have called the Stored Procedure in the Django rest framework. All I just want to pass the user's input in the place of 'demouser@demo.com' and 'NewUser@1' into the Stored Procedure now I have hardcoded value of the email and password which I suppose to get it from the POST request. How could I able to pass the post request in the Stored Procedure. views.py @api_view(['GET', 'POST']) def CheckUserStatusView(request): if request.method == 'GET': users = Tblusers.objects.all() serializer = CheckUserStatusSerializers(users, many=True) return Response(serializer.data) elif request.method == 'POST': cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_CheckOneQUserStatus] @EmailId=%s, @Password=%s', ('demouser@demo.com', 'NewUser@1')) result_set = cursor.fetchall() for row in result_set: row[2] if request.data.get('EmailId') == row[2]: serializer = CheckUserStatusSerializers(data=request.data) if serializer.is_valid(): serializer.save() return HttpResponseRedirect(redirect_to='https://127.0.0.1:4200/#/dashboard') # return Response(status=status.HTTP_308_PERMANENT_REDIRECT) return Response(status=status.HTTP_201_CREATED) serializers.py class CheckUserStatusSerializers(serializers.ModelSerializer): class Meta: model = Tblusers fields ='__all__' models.py class Tblusers(models.Model): UserID = models.AutoField(db_column='UserID', primary_key=True) FullName = models.CharField(db_column='FullName', max_length=255) Emailid= models.CharField(db_column='AccentureID', max_length=255) Password = models.CharField(db_column='Password', max_length=200) -
Adding foreign key data through django rest framework serializer
I am new to django, I have two models User and Todo. User can have multiple todos, while creating the todos I want to pass user_id with it but while including user_id or user field along with request.data, I am getting validation error for Todo fields. Here is the User model and Todo model: class User(AbstractUser): email = models.EmailField(unique=True) password = models.CharField(max_length=128) username = None name = models.CharField(max_length=128) is_email_verified = models.BooleanField(null=True) mobile = models.CharField(max_length=13, validators=[RegexValidator(regex=r'^(\+\d{1,3})?,?\s?\d{8,13}', message="Enter a valid mobile number")], default='+911234567890') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['mobile'] class Todo(models.Model): title = models.CharField(null=False, blank=False, max_length=100) description = models.TextField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: indexes = [ models.Index(fields=['created_at']), models.Index(fields=['updated_at']) ] Here is the Todoserializer: from rest_framework.serializers import ModelSerializer, CharField from todos.models import Todo from users.models import User class TodoSerializer(ModelSerializer): class Meta: model = Todo fields = '__all__' read_only_fields = ['id', 'created_at', 'updated_at'] Here is the view for creating todos: @api_view(['POST']) def create(request): user = request.user todo = TodoSerializer(data={ **request.data, 'user': user.pk }) todo.is_valid(raise_exception=True) todo.save() return Response(status=status.HTTP_200_OK, data={'todo': todo}) The serializer doesn't get validated any time -
Are "max_length" and "choices" in Model's class definition supposed to prevent from inserting invalid values into the database?
I have a situation where i have a model (in Django/python) like: ''' class Box(models.Model): BOX_CHOICES = [('L','Large'),('M','Medium'),('S','Small')] size= models.CharField(max_length=1,choices=BOX_CHOICES, blank=True, null=True) ''' I thought that this would insure that i couldn't add a string like "Humongous" into size field. And yet, i was able to accomplish just that using get_or_create function to insert. Could you please explain how come the max_length and choices did not restrict that from inserting. Thank you! -
How to visualize data in a Django (real-time)
The problem here is that, there are several options I can use in order to display real-time visualization in django. But which one of them is simple enough to be used in teaching a newbie? What I'm trying to do is visualize data which is fetched from an external API. -
how to group by with annotate in django?
I tried absolutely everything with values().annotate() or aggregate() , or by following tutorials with Subquery I cant get what I want, let me explain : There is what I get with QuizzUserItem.objects.filter(examuser=user_exam).values('item__question', 'item') {'item': 759, 'item__question': 429} {'item': 762, 'item__question': 430} {'item': 763, 'item__question': 430} {'item': 767, 'item__question': 431} What I want is to group by item__question and get this result : {'item': 759, 'item__question': 429} {'item': 762,763 'item__question': 430} {'item': 767, 'item__question': 431} I start to think there is absolutely no way :/ What I tried : QuizzUserItem.objects.filter(examuser=user_exam).values('item__question','item').annotate(items_number=Count('item__question')) I got : {'item': 759, 'item__question': 429, 'items_number': 1} {'item': 762, 'item__question': 430, 'items_number': 1} {'item': 763, 'item__question': 430, 'items_number': 1} {'item': 767, 'item__question': 431, 'items_number': 1} or QuizzUserItem.objects.filter(examuser=user_exam).values('item__question').annotate(items_number=Count('item__question')) This one is the closest result that I got : {'item__question': 429, 'items_number': 1} {'item__question': 430, 'items_number': 2} {'item__question': 431, 'items_number': 1} But I have not the item_ids 762,763... Thank you for reading -
TypeError: An asyncio.Future, a coroutine or an awaitable is required in the django-channels
Requirements Python 3.8 asgiref 3.2.0 channels 2.4.0 channels-redis 2.4.2 Django 3.0.9, gunicorn 20.1.0 redis 3.5.3 uvicorn 0.11.5 websockets 8.1 I run channels as gunicorn -w 5 -b 0.0.0.0:8000 --log-level debug -k uvicorn.workers.UvicornWorker config.asgi:application. Also I have nginx as proxy-server. Logs class TokenAuthMiddleware: def __init__(self, inner): self.inner = inner def __call__(self, scope): return TokenAuthMiddlewareInstance(scope, self) class TokenAuthMiddlewareInstance: def __init__(self, scope, middleware): self.middleware = middleware self.scope = dict(scope) self.inner = self.middleware.inner async def __call__(self, receive, send): try: token_key = (dict((x.split("=") for x in self.scope["query_string"].decode().split("&")))).get( "token", None ) except ValueError: token_key = None if token_key is None: self.scope["user"] = AnonymousUser() else: token_data = await get_token_data(token_key) self.scope["user"] = await get_user(token_data["user_id"]) inner = self.inner(self.scope) return await inner(receive, send) -
What is the implication of using request.user over self.request.user
I want to know the major difference between self.request.user (when using generic view View) and request.user (when using a user defined view), at times when I use django's generic View (django.views.generic import View) which has access to the django User model, I'd interact with the authenticated user as request.user and self.request.user without having any problem. For instance, in a django views.py: from django.contrib.auth import get_user_model User = get_user_model() class GetUserView(View): def get (self, request, *args, **kwargs): user_qs = User.objects.filter(username=request.user.username) #Do some other stuffs here class AnotherGetUserView(View): def get(self, request, *args, **kwargs): user_qs = User.objects.filter(username=self.request.user.username) #Do some other stuffs here I realize that the two queryset works fine but I can't still figure out the best to use. -
python Bad Request: /emails
I am trying to make an email web app using python but when I try to press the submit button to send the email this is what I get: [08/Dec/2021 15:26:26] "POST /emails HTTP/1.1" 400 61 Bad Request: /emails [08/Dec/2021 15:26:38] "POST /emails HTTP/1.1" 400 61 Bad Request: /emails ``` Please help! -
How can I solve server error 500 which I am getting during django app deployment on heroku?
When I set debug equals to false my app doesnot work on both local n live env but when I set debug equals true it works all right in local env but gives same server 500 error on live env. This is the github repo for my django project: [https://github.com/Pran1001/HomeFinder] and settings.py file : https://github.com/Pran1001/HomeFinder/blob/main/HOMEFINDER/settings.py below are the logs which I am get from running heroku logs command 2021-12-08T15:01:27.896609+00:00 heroku[router]: at=info method=GET path="/" host=searchyourghar.herokuapp.com request_id=a4b3fa9d-2551-402e-b7ca-5c41c94fbb50 fwd="49.32.177.39" dyno=web.1 connect=0ms service=21ms status=500 bytes=409 protocol=http -
File upload returns no HTTP status
I have a Django / React application hosted in AKS. React's build is hosted statically with Nginx. The Nginx container is exposed through a ClusterIP, Ingress & Nginx-Controller. The In this app, I'm doing a file upload, which returns nothing. Not an error, not an HTTP status code, nothing. That makes debugging very hard. This doesn't happen locally, and it only happens with files bigger than approx 10mb. Already increased the client_max_body_size in the default.conf of the nginx host. Can't find anything in the Controller docs that indicates a too large filesize, and this would also result in a HTTP 413. Anyone familiar with this? In React I simply use axios with formData: let formData = new FormData(); axios.post(`${API_SERVER}/builds`, formData).then(response => { console.log(response); }).catch(error => console.log(error)); The HTTP response: undefined undefined undefined date: Wed, 08 Dec 2021 15:27:35 GMT content-type: text/html content-length: 176 strict-transport-security: max-age=15724800; includeSubDomains X-Firefox-Spdy: h2 -
Cannot successfully pass foreign_key reference to PUT request in Django REST
I am getting into Django REST and I am trying to use it for a backend of type of crypto currency tracker for my use. However I have been stuck on an issue for a few days.. I have the following models.py: class Coin(models.Model): sign = models.CharField(max_length=50, primary_key=True) # capitalize all entries name = models.CharField(max_length=50, null=False) amount = models.DecimalField(max_digits=20, decimal_places=2, null=False) price_each = models.DecimalField(max_digits=20, decimal_places=2, null=False) purchased_on = models.DateField(null=True) def __str__(self): return self.sign def save(self, *args, **kwargs): self.sign = self.sign.upper() return super(Coin, self).save(*args, **kwargs) class Price(models.Model): coin = models.ForeignKey(Coin, related_name="prices", on_delete=models.CASCADE) day_date = models.DateField(null=False) current_price = models.DecimalField(max_digits=20, decimal_places=2, null=False) def __str__(self): timestamp = self.day_date.strftime("%d-%b-%Y") return timestamp and serializers.py: class PriceSerializer(serializers.ModelSerializer): coin_sign = serializers.PrimaryKeyRelatedField(queryset=Coin.objects.all(), source='coin.sign') class Meta: model = Price fields = ['id', 'day_date', 'current_price', 'coin_sign'] def create(self, validated_data): return Price.objects.create(**validated_data) class CoinSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True, read_only=False) class Meta: model = Coin fields = ['sign', 'name', 'amount', 'price_each', 'purchased_on', 'prices'] def create(self, validated_data): return Coin.objects.create(**validated_data) I am having trouble defining a view with PUT to create a new price entry in view.py: class AddPrice(APIView): def put(self, request, sign, format=None): coin = get_object_or_404(Coin, sign=sign.upper()) request.data['coin_sign'] = coin serializer = PriceSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is the … -
How to get Todo items with today as deadline
so i'm still creating my todo list app, and i want to render all the items that has todays date as the deadline so as to remind the user of the pending tasks. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class ToDo(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) todo = models.CharField(max_length=50) description = models.TextField(max_length=200, blank=True) created = models.DateField(auto_now=True) end = models.DateField() start = models.DateField() completed = models.BooleanField(default=False) def __str__(self): return f'{self.owner} - {self.todo}' views.py def index(request): activities = ToDo.objects.all() today = ToDo.objects.get(end=datetime.date.today) todo = ToDo.objects.count() complete = ToDo.objects.filter(completed=True).count() percent = complete * 100 // todo if request.method == 'POST': try: search = request.POST.get('todo') activities = ToDo.objects.filter(todo__icontains=search) except: search = request.POST.get('end') activities = ToDo.objects.filter(end=search) context = { 'activities' : activities, 'percent' : percent, 'today' : today, } return render(request, 'home.html', context) i imported datetime in my views.py -
Title cannot contain "Ask a public question". Please provide a title that summarizes your question. For assistance, see: How do I ask a good question?
A standard blockquote is indented A nested blockquote is indented more You can nest to any depth You can nest to any depth -
ManyToMany Model query
I have 2 models Project and Investor Project model has a field called project_investors with a ManyToMany to the Investor model. Models class Investor(models.Model): investor_name = models.CharField(max_length=50, blank=False, unique=True) investor_website = models.URLField(max_length=100, blank=True) investor_portfolio_website = models.URLField(max_length=100, blank=True) investor_description = models.TextField(blank=True) investor_investments = models.TextField(blank=True) def __str__(self): return str(self.investor_name) class Project(models.Model): project_name = models.CharField(max_length=50, blank=False, unique=True) project_website = models.URLField(max_length=50, blank=True) project_description = models.TextField(blank=True) project_investors = models.ManyToManyField(Investor, blank=True) def __str__(self): return str(self.project_name) I then have a page the shows the Investor details and im trying to show which projects have been linked to this investor. myview.py @login_required def show_investor_details(request,investor_id): investor = Investor.objects.get(pk=investor_id) form = InvestorForm(request.POST or None, instance=investor) project = Project.objects.all() project_list = get_object_or_404(Project, project_investors=investor_id) return render(request, 'pages/investor_details.html', {"investor": investor, "form": form,"project": project,'project_list':project_list}) Im not sure what is the correct query to pass in here project_list = get_object_or_404(Project, project_investors=investor_id) as this error is thrown: 'Project' object is not iterable Or maybe I have the model structure incorrect? -
Reverse for 'delete_post' with arguments '('',)' not found. 1 pattern(s) tried: ['article/(?P<pk>[0-9]+)/remove$']
i was creating a simple blog site and I created buttons to delete7edit , but as soon as I try to reset the app and go there I get this error ( title ) this is my code view.py: from django.views.generic import ListView from . models import Article from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .forms import PostForm, EditForm from django.urls import reverse_lazy class ArticleListView(ListView): model = Article template_name = 'home.html' class ArticleDetailView(DetailView): model = Article template_name = 'detail.html' class AddPostView(CreateView): model = Article form_class = PostForm template_name = 'add_post.html' #fields = '__all__' #fields = ('title', 'body') class UpdatePostView(UpdateView): model = Article form_class = EditForm template_name = 'update_post.html' #fields = ['title', 'title_tag', 'body'] class DeletePostView(DeleteView): model = Article template_name = 'delete_post.html' success_url = reverse_lazy('home') urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.ArticleListView.as_view(), name='home'), path('article/<int:pk>', views.ArticleDetailView.as_view(), name='detail'), path('add_post/', views.AddPostView.as_view(), name='add_post'), path('article/edit/<int:pk>', views.UpdatePostView.as_view(), name='update_post'), path('article/<int:pk>/remove', views.DeletePostView.as_view(), name='delete_post'), ] help me please, I'm new on django and i don't know things yey -
Product matching query does not exist
i'm building a small webstore , in the product page i put the order form using FormMixin and TemplateView, when i submit the order i get a Page Not Found error "No Order matches the given query." Bellow you can check the code Models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=255, unique=True, ) description = models.TextField(max_length=1500) class Meta: verbose_name_plural = "categories" def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() nominal_price = models.PositiveIntegerField(verbose_name='prix normal',) reduced_price = models.PositiveIntegerField(blank=True, null=True) quantity = models.PositiveIntegerField(default=10) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png") def __str__(self): return self.name class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.IntegerField() city = models.CharField(max_length=100) email = models.EmailField(null=True) class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) Views.py class ProductDetailView(FormMixin, TemplateView): model = Product template_name = 'product.html' form_class = OrderForm def get_success_url(self): return reverse('index') def post(self, request, *args, **kwargs): context = self.get_context_data() form = OrderForm(request.POST) if context['form'].is_valid(): product = get_object_or_404(Order, product__name=self.kwargs['product_name']) customer = form.save(commit=False) Order.objects.create(product=product, customer=customer) form.save() return super(TemplateView, self) def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context['product'] = Product.objects.get(name=self.kwargs['product_name']) context['form'] = self.get_form() return context forms.py class OrderForm(forms.ModelForm): class … -
Django: I get: Cannot query "admin": Must be "Follow" instance in my code when trying to implement unfollow button
I'm a beginner and I'm trying to create a small network project in which users can follow each other. I have implemented the follow button right, so it updates my models and displays proper info to users, but I can't get unfollow to work properly. I'm guessing it's something to do with the way I implemented follow model (with many to many field), but I'd like to implement it this way for practice... Anyhow, here's the code: Models: class User(AbstractUser): pass class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_follow") following = models.ManyToManyField(User, blank=True, related_name="followers") And view: def users(request, username): """Displaying user profiles""" if request.method == "POST": user = request.user profile = User.objects.get(username=username) follow = Follow(user=user) follow.save() if "unfollow" in request.POST: profile.followers.remove(user) follow.following.remove(profile) return HttpResponseRedirect(reverse('users', args=(username,))) elif "follow" in request.POST: follow.following.add(profile) return HttpResponseRedirect(reverse('users', args=(username,))) This code yields in: "ValueError at /users/test Cannot query "admin": Must be "Follow" instance." at the profile.followers.remove(user) line... Playing with it in shell I found out (at least I think so) that the line under it (follow.following.remove(profile) - which by the way was there before I tried with the profile.followers.remove(user)) removes the profile from Follow model, but for some reason it is not by itself updated in the … -
How to fet a queryset for every object in queryset
Let's assume I have an Employees model. There are 3 different titles such as "Top manager", "Sales manager" and "Sales representative" and field "reports_to". Top manager doesn't report to anyone, Sales managers report to Top and Sales representatives report to Managers. I have a list view to see employees list, it shows employees who reports to higher employee as described above. Also I try to list employees who reports to those who report to me. Like (I'm logged in as a Top manager) --Here goes Sales manager ----Here goes this manager's Sales representatives So far I achieved getting manager's representatives, but only for the first manager in the queryset. The question is: how do I get separate querysets of Representatives for every Manager in queryset? Additional question: am I right in using prefetch_related() here? View: def get_current_users_employee(user): try: employee = Employees.objects.get(user=user) return employee except User.DoesNotExist: raise Http404("Employee doesn't exist for this user.") class EmployeesListView(LoginRequiredMixin, ListView): model = Employees template_name = 'employees/employees_list.html' context_object_name = 'employees_list' fields = ['last_name', 'first_name', 'title', 'birth_date', 'reports_to'] def dispatch(self, request, *args, **kwargs): handler = super().dispatch(request, *args, **kwargs) emp = get_current_users_employee(self.request.user) if (emp.title == "Sales representative"): raise PermissionDenied return handler def get_queryset(self): current_emp = get_current_users_employee(self.request.user) return super().get_queryset().filter(reports_to=current_emp) … -
how to perform Rank query in Django
I am stuck at this point and this query seems a bit tricky to me so basically i am getting data from devices in periodic intervals 'lets say 3 hours' But every device is sending data twice on every interval(3 hours), i am required to extract data that is send last(in intervals) "date": "2021-11-28", "time": "12 : 35", "meter": "70F8E7FFFE10C495", "dr": 3, "date_received": "2021-11-28T18:05:20.473430+05:30", }, { "id": 2, "date": "2021-11-28", "time": "12 : 37", "meter": "70F8E7FFFE10C459", "date_received": "2021-11-28T18:07:09.980403+05:30", }, { "id": 3, "date": "2021-11-28", "time": "12 : 37", "meter": "70F8E7FFFE10C459", "dr": 3, "date_received": "2021-11-28T18:07:11.533388+05:30", }, { "id": 4, "date": "2021-11-28", "time": "12 : 50", "meter": "70F8E7FFFE10C463", "date_received": "2021-11-28T18:20:44.197284+05:30", }, { "id": 5, "date": "2021-11-28", "time": "12 : 56", "meter": "70F8E7FFFE10C47D", "date_received": "2021-11-28T18:26:43.221316+05:30", }, { "id": 6, "date": "2021-11-28", "time": "12 : 56", "meter": "70F8E7FFFE10C47D", <---- only want to get this occurrence "date_received": "2021-11-28T18:26:44.925292+05:30", }, So if device : 70F8E7FFFE10C459 sends data twice i want to retrieve only last sent data , and this needs obj in queryset , i was told about RANK concept don't understand how to apply that here -
Django mysql query to queryset
i really want to change select u.name, p.id, p.title, p.keyword_id, (SELECT count(id) FROM postings where user_id = u.id) as total_posting from users u JOIN postings p ON p.user_id = u.id where p.keyword_id = 14 this mysql query to django queryset... help me :/ elements are from users.models import User from postings.models import Posting from django.db.models import Count,Subquery ... helllppppp plzzz ㅜ,ㅜ -
How to mock and test a django view including external api call
I want to test a django view which includes a call to an external API. The API call is wrapped up by another package (jira). When the view is called a jira ticket is created for a Project (model). How would I properly test the view while preventing that the external API is called. The view looks like this: class RequestHelp(View): def get(self, context, pk=None, **response_kwargs): # get the project to create the ticket for project = Project.objects.get(id=pk) # initialize the jira client jira = JIRA( server=settings.JIRA_URL, basic_auth=(settings.JIRA_USERNAME, settings.JIRA_PASS), ) # create the ticket in jira new_issue = jira.create_issue( project=settings.JIRA_PROJECT, summary= project.title , description="Would you please be so nice and help me", reporter={"name": "My User"}, issuetype={"name": "An Issue"}, ) return HttpResponseRedirect("/") The test at the moment looks like this: class TestRequestHelp(TestCase): @classmethod def setUpTestData(cls): cls.std_user = User.objects.create_user( username="john", email="john@doe.de", password="secret", is_staff=False, is_superuser=True, ) def test_get_help_logged_in(self): self.client.login(username="john", password="secret") project, status = Project.objects.get_or_create(title="Test") response = self.client.get(f"/project/help/{project.pk}", follow=True) self.assertEqual(200, response.status_code) A "normal" test of the view works but always creates a ticket which is not desirable. Any help with this would be appreciated. -
How can I autofill a field in my django form in class based view?
I create an opportunity for users to comment on the book. I have a list of books, where all the books in the database are placed, and also a detail book for each book. I created a form for the possibility of commenting in detail book, where I pass various fields, but some I want to be autofilled not by the users themselves, such as the title of the book and the author. I managed to do it with the author, but the title of the book does not work. I would be grateful if you can help with this. models.py import uuid from django.db import models from django.db.models.enums import TextChoices from django.urls import reverse from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User class Genre(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) image = models.ImageField( upload_to="photos", default=None, blank=True, null=True) author = models.ForeignKey("Author", on_delete=models.SET_NULL, null=True) summary = models.TextField() isbn = models.CharField(max_length=10, unique=True, blank=True, null=True) genre = models.ManyToManyField("Genre", related_name="book_genre") publisher = models.ManyToManyField("Publisher") languages = models.ManyToManyField("Language") publication_date = models.DateTimeField(default=timezone.now) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse("book_detail", kwargs={"pk": self.pk}) class Meta: ordering = ["-created_date"] constraints = [ models.UniqueConstraint( fields=["title"], … -
"depth" in django rest framework: How to access values?
Here my requirement is to access values in the below structure which is get by using "depth" in the serializer. serializers.py class Meta: model = Course fields = ("is_favorite", "backgroundcolor", "instructor", "instructor_rating", "review_status", "id", "name", "description", "is_free", "image", "keyarea", "subject", "course_type", "beneficiary", "section", "datetime_created", "general_status", "review_status", "difficulty", "publish_date", "enrollment", "revenue", "category", "created_by", 'last_modified_by', 'course_rating', 'enrollment_type', 'expiry_data', "course_banner") depth = 3 The result structure: { "status": 200, "data": { "course": { "is_favorite": false, ..... ..... ..... "section": [ { "id": "5bf83a1c-e240-4907-9f71-e449644860b1", "deleted": null, "datetime_created": "11/29/2021 09:33 AM", "datetime_updated": "11/29/2021 09:33 AM", "name": "section1", "code": "22833", "description": "Description", "is_locked": true, "is_free": true, "modules": [ { "id": "0e82f2a5-6365-4206-b9e3-cd4e8e54f16c", "deleted": null, "datetime_created": "11/29/2021 09:32 AM", "datetime_updated": "11/29/2021 09:32 AM", "name": "module1", "description": "Description", "is_free": true, "videos": [ { "id": "8c7e70ec-703d-4c07-97ff-c69202451de8", "deleted": null, "datetime_created": "11/29/2021 08:05 AM", "datetime_updated": "11/29/2021 08:05 AM", "video_name": null, "description": null, "duration": "03:20:00", "create_date": "11/29/2021 08:05 AM", "video_type": "micro", "file_url": "https://vimeo.com/369126918", "general_status": "High", "review_status": "Draft", "created_by": null }, { "id": "ec4e3ce7-69e9-45d6-b00f-60f0012044bb", "deleted": null, "datetime_created": "11/29/2021 08:02 AM", "datetime_updated": "11/29/2021 08:02 AM", "video_name": null, "description": null, "duration": "00:01:40", "create_date": "11/29/2021 08:02 AM", "video_type": "micro", "file_url": "https://vimeo.com/369126918", "general_status": "High", "review_status": "Draft", "created_by": null } ] } ] } ], ...... ...... }, "success": … -
Python & Django - 'ModuleNotFoundError: No module named 'GoalCategoryTest'' when trying to import TestCase
So I have this TestCase file CategorySearchTest.py class CategorySearchTest(TestCase): @classmethod # Generates Test DB data to persist throughout all tests def setUpTestData(cls) -> None: cls.access_token = get_test_user_access_token() cls.user = get_or_create_test_user_in_DB() cls.goal_category_name_list = ['Health', 'Fitness', 'Art', 'Relationships', 'Artist'] I'm trying to import this in the init.py file in the same folder so I can run all the tests in this folder with the command python manage.py test <root>\test\CategoriesTest. my __init__.py file looks like this from GoalCategoryTest import * then here's my folder structure I'm getting the error from my __init__.py file which is ModuleNotFoundError: No module named 'GoalCategoryTest'. Why is this happening? I've tried from GoalCategoryTest import * and import GoalCategoryTest and both give the same error. -
how i can set the margin-left of the page to don't let the data spread along the width of the paper
Am newbie and am trying to use the library "reportlab" to generate the PDF, I want to fix the margin-left of the page but i did'nt know how i can do that : this is my code: c = canvas.Canvas(buf, bottomup=0) c.translate(inch,inch) textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 6) posts = Post.objects.all() lines = [] for post in posts: lines.append(post.title) lines.append(post.content) This is how it looks like : enter image description here But what i want is to fix the margin left