Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get relationship with one-to-many on same table?
I am using django and rest api. And I have two models: class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) images = models.ImageField(upload_to="photos/categories") category = models.ForeignKey("Category", on_delete=models.CASCADE, related_name='part_of', blank=True, null=True) date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) description = models.TextField(max_length=1000, blank=True) legislation = models.TextField(max_length=1000, blank=True) review = models.TextField(max_length= 000, blank=True) eaza = models.TextField(max_length=1000, blank=True) class Meta: verbose_name = "category" verbose_name_plural = "categories" def __str__(self): return self.name class Animal(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) images = models.ImageField(upload_to="photos/categories") category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='animals') date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) description = models.TextField(max_length=1000, blank=True) legislation = models.TextField(max_length=1000, blank=True) review = models.TextField(max_length=1000, blank=True) eaza = models.TextField(max_length=1000, blank=True) class Meta: verbose_name = "animal" verbose_name_plural = "animals" def __str__(self): return self.name And my serializer looks: class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = ['id','name', 'description'] class CategorySerializer(serializers.ModelSerializer): animals = AnimalSerializer(many=True) class Meta: model = Category fields = ['id','category_id','name', 'description', 'animals'] and views.py: class CategoryViewSet(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() @action(methods=['get'], detail=False) def mainGroups(self,request): mainGroups = Category.objects.filter(category_id__isnull=True) serializer = self.get_serializer(mainGroups, many=True) return Response(serializer.data) and urls.py: router = routers.DefaultRouter() router.register('groups', CategoryViewSet) urlpatterns = [ path('', include(router.urls)) ] So if I go to: http://127.0.0.1:8000/djangoadmin/groups/ I get as output: [ { "id": 11, "category_id": null, "name": "zoogdieren", "description": … -
Django block content
I am trying out block content in my django project but when i type in my code in a html file like so <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="a"> {% block content %} {% endblock %} </div> </body> </html> {% block content %} {% endblock %} these two codes won't work and they don't turn yellow as they should. could somebody help me? -
How can I Automatically post my django website blog on my fb page
I have a django blog website whenever I post a blog I want my blog to be posted on my fb page automatically how can I do that? Can Anyone help? Post my django website blog on my fb page automatically. -
Is it good practice to evoke object and re-assign value in Python/Django?
views.py from rest_framework import views from rest_framework.response import Response from .models import Category from .services.get_categories import cached_categories from .serializers import CategorySerializer class CategoryTreeList(views.APIView): def get(self, request, format=None): queryset = Category.objects.all() cached_categories(queryset) serializer = CategorySerializer(cached_categories.get_cached_root_nodes(), many=True) return Response(serializer.data) serializers.py from .models import Category from rest_framework import serializers from .services.get_categories import cached_categories class CategorySerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() class Meta: model = Category fields = ('id', 'name', 'children', ) def get_children(self, obj): children = cached_categories.get_children(obj) if children: return CategorySerializer(children, many=True).data else: return [] get_categories.py from ..models import Category class CachedCategories: def __init__(self): self.queryset = None def __call__(self, queryset): self.queryset = queryset def split_on_dicts(self): objects_by_depth = {} for i in [obj.depth for obj in self.queryset]: objects_by_depth.update({f"{i}": [obj for obj in self.queryset if obj.depth == i]}) return objects_by_depth def get_children(self, parent: Category): categories = self.split_on_dicts().get(f"{parent.depth + 1}") children = [] if categories: for obj in categories: if obj.path.startswith(parent.path) and \ obj.depth == parent.depth + 1: children.append(obj) return children def get_cached_root_nodes(self): return self.split_on_dicts().get("1") cached_categories = CachedCategories() Explaining what I want. I built django app with nested categories. And I wanted to pass categories to serializator with just one query. So I did it. Then, I understood that my class CachedCategories (in get_categories.py) works only once, when … -
I am saving EmailDb filed username and userpassword to another Emails models but it is saving null data in Emails db with refresh django
Null value or empty value saved with each refresh, even click button submit duplicate value, please find the following models and views file. please look at envlope button in the image that is submit button which create another model db called Emails. fdisply.html {% for i in obj %} <tr> {% if i.id %} <th scope="row">{{forloop.counter0|add:obj.start_index}}</th> <td>{{i.institution}}</td> <td>{{i.fullname}}</td> <td>{{i.email}}</td> <td>{{i.contact}}</td> <td>{{i.position}}</td> <td><img src={{i.uploaddata.url}} class="img-fluid img-thumbnail" alt={{i.fullname}} style="width:100px; height: 60px"></td> <td> <a href="{% url 'update' i.id %}" class="btn btn-warning btn-sm"><i class="fa-regular fa-pen-to-square"></i></a> <form action="{% url 'delete' i.id %}" method="POST" class="d-inline"> {% csrf_token %} <button type="submit" class="btn btn-danger btn-sm"> <i class="fa-regular fa-trash-can"></i> </button> </form> <!-- sent data --> <form method="POST" class="d-inline"> {% csrf_token %} <div class="d-none"> <input type="text" name="email" id="email" class="form-control w-50 form-row" value="{{i.useremail}}" required> <input type="text" name="password" id="password" class="form-control w-50 form-row mt-1" value="{{i.userpassword}}" required> </div> <button type="submit" class="btn btn-danger btn-sm"> <i class="fa-solid fa-envelope-circle-check"></i> </button> </form> </td> </tr> {% endif %} {% endfor %} models.py class EmailDb(models.Model): institution = models.CharField(max_length=300, blank=True, null=True) fullname = models.CharField(max_length=50, blank=True, null=True) contact = models.IntegerField() email = models.CharField(max_length=300, blank=True, null=True) position = models.CharField(max_length=100, blank=True, null=True) uploaddata = models.FileField(upload_to='appointment_letter') useremail = models.CharField(max_length=100, blank=True, null=True) userpassword = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.fullname class EmailS(models.Model): ename = models.CharField(max_length=100, … -
Assertion error upon using customuser model with allauth
I tried building a custom user model while using django allauth, and while trying to makemigrations for the model, I was getting an error saying that their is no username field in my model, upon doing what I could find on that problem here, I'm getting this error:- Traceback (most recent call last): File "/project-sirji/manage.py", line 23, in <module> main() File "/project-sirji/manage.py", line 19, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/usr/local/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/usr/local/lib/python3.11/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/usr/local/lib/python3.11/site-packages/allauth/account/models.py", line 9, in <module> from . import app_settings, signals File "/usr/local/lib/python3.11/site-packages/allauth/account/app_settings.py", line 373, in <module> app_settings = AppSettings("ACCOUNT_") ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/allauth/account/app_settings.py", line 21, in __init__ not self.AUTHENTICATION_METHOD == self.AuthenticationMethod.EMAIL ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AssertionError Here's my models.py file:- from django.db import models from … -
PageSpeed speed index slow on practically empty React app
I am using Django on the backend and running React on the frontend inside Django app. I have created very basic frontend with loading animation until React loads in and few components with navigation and heading. That's basically it. I wanted to have a very basic starting point and test it for page speed so I deployed the project to railway and tested it out. But even after fixing all the problems that PageSpeed Insight suggested I can't get the mobile version above 88. Under the network tab I can see that main.js is by far the biggest content download but at the same time 324kB doesn't seem like too much. I don't know what else to improve anymore as it's such a basic app. What is causing the main.js to be downloaded so slowly? -
Dj-rest-auth set HTTP-only JWT cookies [closed]
I know some of you might have been searching for answers on how to set JWT HTTP-only cookies in response. I finally found an answer how to do it, and it's actually easy. You can visit my repo and scroll down to the README.MD file -
Getting 401 error : "invalid_client" in django-oauth-toolit
I am trying to have an Ouath2 access token based authentication. I am using django-oauth-toolkit for that. I have registered my app on http://localhost:8000/o/applications. However, When I tried to hit the URL http://localhost:8000/o/token/ from the react-app . I got 401. Here is my the useEffect hook that I used for calling that URL : useEffect(() => { fetch("http://localhost:8000/o/token/", { body: new URLSearchParams({ grant_type: 'client_credentials', client_id: 'my_client_id', client_secret: 'my_client_secret' }), headers: { "Content-Type": "application/x-www-form-urlencoded" }, method: "POST" }).then((res)=>{ console.log(res) }) }, []) Will look forward to some comments and solutions. -
Django webpack not loading images from static files
I'm in the process of making a website using django and react. I'm using client side rendering in react, instead of handling all the urls with django, and I stumbled upon the problem of not being able to refresh pages from urls other than the base url. From what I understood the easiest solution was webpack and it's historyApiFallback. Anyway, now that I've configured webpack, historyApiFallback doesn't work, and my static images will no longer load... Hopefully someone can help me out here, need it big time. webpack.config.js const path = require("path"); const BundleTracker = require('webpack-bundle-tracker'); const HtmlWebpackPlugin = require("html-webpack-plugin"); var config = { context: __dirname, entry: './src/index.js', output: { path: path.join(__dirname, 'assets/dist'), filename: "main.js", publicPath: '/' }, devServer:{ historyApiFallback: true }, plugins: [ new BundleTracker({ filename: './webpack-stats.json' }), new HtmlWebpackPlugin({ template: './public/index.html' }) ], devtool: 'hidden-source-map', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /\.(png|jpg|jpeg|gif)$/, type: 'asset/resource', use: [ 'url-loader' ] }, ] } } module.exports = () => { return config }; settings.py FRONTEND_DIR = os.path.join(BASE_DIR, 'frontend') STATIC_URL = 'static/dist/' STATIC_ROOT = os.path.join(FRONTEND_DIR, "assets/dist/") STATICFILES_DIRS = ( os.path.join(FRONTEND_DIR, "static/dist/"), ) MEDIA_URL = '/Images/' … -
How can I solve this "violates not-null constraint"?
I alway get this error, even I put default value on the avg_winning_trade: django.db.utils.IntegrityError: null value in column "avg_winning_trade" of relation "trading_summary" violates not-null constraint DETAIL: Failing row contains (43897354-d89b-4014-a607-a0e6ee423b52, 1, 2023-02-05 11:09:56.727199+00, null, 1, 19, 1, 0.00, null, -1.01, -1.01, 0, 0, 0.00, 0%, 0.00). The second null value is avg_winning_trade who cause the error here, I don't know why it is null here this is my model class Summary( ActivatorModel, Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) starting_balance = models.DecimalField(default=0, max_digits=10, decimal_places=2) total_number_of_trades = models.PositiveIntegerField(default=0) total_number_of_winning_trades = models.PositiveIntegerField(default=0) total_number_of_losing_trades = models.PositiveIntegerField(default=0) total_number_of_be_trade = models.PositiveIntegerField(default=0) largest_winning_trade = models.DecimalField(default=0, max_digits=10, decimal_places=2) largest_losing_trade = models.DecimalField(default=0, max_digits=10, decimal_places=2) avg_winning_trade = models.DecimalField(default=0, max_digits=10, decimal_places=2) avg_losing_trade = models.DecimalField(default=0, max_digits=10, decimal_places=2) total_trade_costs = models.DecimalField(default=0, max_digits=10, decimal_places=2) trade_win_rate = models.CharField(max_length=10) This is the table Column | Type | Collation | Nullable | Default | Storage | Compression | Stats target | Description --------------------------------+--------------------------+-----------+----------+---------+----------+-------------+--------------+------------- id | uuid | | not null | | plain | | | status | integer | | not null | | plain | | | activate_date | timestamp with time zone | | | | plain | | | deactivate_date | timestamp with time zone | | | | plain | | … -
Unable to get the response from trpc mutation in trpc-v10 using drf and django as backend
I have an app that uses t3-app as boiler plate with tailwind and trpc and django as my backend with drf to create api endpoints. I am not able to get the data back from a login endpoint that is a generic apiview. class LoginView(generics.GenericAPIView): authentication_classes = [] permission_classes = [] def post(self, request, *args, **kwargs): username = request.data.get("username") password = request.data.get("password") user = authenticate(username=username, password=password) if user: return Response(data={ 'data': { "token": Token.objects.create(user=user).key, 'username': user.get_username(), 'email': user.email, 'group': [g.name for g in user.groups.all()] } }, content_type='application/json') else: return Response({"error": "Wrong Credentials"}, status=400) When I try this end point with Postman, it works as below: but when I use trpc to fetch this endpoint I don't get any response but the token is generated my trpc router code is: import { z } from "zod"; import { router, publicProcedure } from "../trpc"; export const commonRouter = router({ login: publicProcedure .input( z.object({ username: z.string(), password: z.string().min(4, "Password must be at least 4 characters"), }) ) .mutation(async ({ input }) => { console.log("Hello from login mutation") console.log('input', input) try { // const router = useRouter(); const data = { username: input.username, password: input.password, }; const options = { method: "POST", headers: { … -
Django: avoid multiple DB queries for recursive model
I have following models: class Topic(models.Model): ... class Article(models.Model): ... class ArticleInTopic(models.Model): topic = models.ForeignKey(Topic, on_delete=models.PROTECT) article = models.ForeignKey(Article, on_delete=models.PROTECT) depends_on = models.ForeignKey(ArticleInTopic, on_delete=models.PROTECT) class Meta: unique_together = ('topic', 'article', 'depends_on') With this models set I'm trying to express the following situation: there are some studying topics, each consists of multiple articles. However, in order to learn a topic one should read the articles related to the topic but not in any order, rather in order defined by article dependencies. This means that in context of a topic an article may have another article which is required to be read before reading this article. It is guaranteed that the article on which the current article depends on comes from the same topic. So, basically, this whole structure looks like an acyclic (it is guaranteed) graph with parent-child nodes relation. In the business logic of my app I'm going to sort the graph topologically so I can tell the user which Article to read 1st, 2nd, etc. However, the problem is the way Django fetches ForeignKey's data from the database. AFAIK it uses N+1 request to fetch all foreign keys. There is a solution to it - using select_related but this … -
Trying to create a one-time calculated field in Django model
Building my first Django app, and I'm running into a snag. I have a Django model that creates Job objects, and I want each job code to be unique and auto-generated, with a particular format. The format is: aaaMMnnYYYY, where aaa is a 3-letter client identifier that we set, nn is a counter that represents the nth job from that client in that month., and MM and YYYY are month and year respectively. e.g., for the 3rd job from client "AIE" in feb 2023, the ID would be AIE02032023. Using a calculated field with the @property decorator causes the field to be continuously updated, so I'm trying to do this by modifying the save() method. There's also a related Cost object that has Job attributes via Foreign Key. The way I have it now, when I add a Cost, the 'iterating' part of the job code iterates, changing the job code, which causes uniqueness errors as well as URL errors (I'm using the job code in the URLConf. As a side note, I'd also like to be able to override the job code. Is there a way to set flags within a model, such as job_code_overridden = False, etc.? Here's … -
Django FirstApp
`# This is the url :Link views.py code: ` from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the poll index.")` urls.py code: (this is inside polls app urls.py file) : ` from django.urls import path, include from django.conf import settings from . import views urlpatterns = [ path(r'^$', views.index, name='index'), ] ` urls.py code : ( this is root urls.py file code): ` from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] ` here my run command : python manage.py runserver 8080 Unable to run this I am getting an error: `Page not found (404) Request Method: GET Request URL: http://35527a91f40c4e228d6c464d8a8c8487.vfs.cloud9.eu-west-1.amazonaws.com/ Using the URLconf defined in PollApp.urls, Django tried these URL patterns, in this order: poll/ admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.` Today I tried to run, But I am getting an error like this. ` -
This backend doesn't support absolute paths Django Google Storage
I have a Django app in Compute Engine. I set up a Google Cloud Storage as storage for my media files. In one endpoint, you can request for the file information including the file path. When I POST for this endpoint it returns: This backend doesn't support absolute paths. For simplicity my view for the endpoint look like this: class FilesView(APIView): permission_classes = (permissions.AllowAny,) def post(self, request): ... path = layer.file.path response_message = {'file': path } return Response(response_message, status.HTTP_200_OK) I have done the following: Create a service account and download the JSON. Configure it to my Django settings. I added the service account to the permissions in the bukcet i.e. set as Storage Admin. I added allUsers to have permission: Storage Legacy Object Reader. I changed the bucket from Uniform to Fine-grained. Here is in my settings: DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'sample-bucket' GCP_CREDENTIALS = os.path.join(BASE_DIR, 'sample-bucket-credentials.json') GS_CREDENTIALS = service_account.Credentials.from_service_account_file(GCP_CREDENTIALS) -
Link Django models together via GenericKey?
i have the following models: class Team(models.Model): users = models.ManyToManyField("User") class User(AbstractUser): ... class Subscription(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE) name = models.CharField(max_length=64) class Package(models.Model): name = models.CharField(max_length=64) # packageA, packageB max_activation_number = models.PositiveIntegerField(default=1) class Activation(models.Model): subscription = models.ForeignKey("Subscription", on_delete=models.CASCADE) package = models.ForeignKey("Package", on_delete=models.CASCADE) created = models.DatetimeField() class PackageA(models.Model): ... class PackageB(models.Model): ... A team has one subscription and it can activate one or more package and the same package could be activated more than one time. (number of times specified with "max_ativation_number") Example: A team has a subscription called Suite and the available packages are: EmailAccount and Calendar The team choose to activate 3 EmailAccount and 2 Calendar (packages are not tied to each other) For that reason the team could activate the same package more times. For every activation i need to create a new instance on PackageA or PackageB (it depends on the choice a team made) and then i should "link" to that instance somehow. Should i use GenericKey field inside Activation model? I not only need the name of the chosen package but I also need to figure out which instance. -
Firebase get method returning a list for one object of objects and a dict for another
Im using django with firebase and have 2 objects of objects in the database, everything about them is the same, the way i store them in the database, the way im trying to access them. When i use the get method phones = ref.child('Data').child('users').child(uid).child('phones').get() computers = ref.child('Data').child('users').child(uid).child('computers').get() (absolutely the same way) for the fisrt one i get a list of dict looking like that [{'OS': 'Windows', 'battery': 2000.0, 'memory': 16.0, 'popularity': 200.0, 'price': 2429.73, 'screen': 6.0}, {'OS': 'Windows', 'battery': 1600.0, 'memory': 32.0, 'popularity': 200.0, 'price': 1907.28, 'screen': 6.0}] and for the second one i get a dict of dict like this one {'12': {'cd': 'no', 'hd': 5.0, 'multi': 'no', 'premium': 'yes', 'price': 1397.0, 'ram': 5.0, 'screen': 2.0, 'speed': 5.0}, '13': {'cd': 'yes', 'hd': 45.0, 'multi': 'no', 'premium': 'no', 'price': 1999.0, 'ram': 8.0, 'screen': 14.0, 'speed': 120.0}} the second one also has their id below which they are stored (i store them like that ref = db.reference("Data/users/"+str(request.session['user_id'])+'/phones/'+str(phone.id)) telephone = phone.save_to_firebase() ref.set(telephone), ref = db.reference("Data/users/"+str(request.session['user_id'])+'/computers/'+str(comp.id)) computer = comp.save_to_firebase() ref.set(computer)) i want both of them to look like the second and have no idea why they differ I checked everything but there is not a single difference about how the objects are treated -
fromisoformat: argument must be str Django
TypeError at /profile/updateAuction/updateData/1 fromisoformat: argument must be str I have this problem when I want to update expiration date by the form, but it changes in admin panel. But I want to make changeable for user. views.py @permission_classes([IsOwnerOrReadOnly]) @login_required(login_url='/accounts/login') def updateData(request, id): title = request.POST['title'] description = request.POST['description'] expiration_date = (request.POST['expiration_date'], f'%m/%d/%Y') lot_cost = request.POST['lot_cost'] image = request.POST['image'] updatedUser = Auction.objects.get(id=id) updatedUser.description = description updatedUser.expiration_date = expiration_date updatedUser.lot_cost = lot_cost updatedUser.cover = image updatedUser.title = title updatedUser.save() return HttpResponseRedirect(reverse('index')) models.py class Auction(models.Model): title = models.CharField(max_length=255, null=False, blank=False) image = models.ImageField(upload_to='images', default='images/no-image.svg') description = models.TextField(null=False, blank=False) lot_cost = models.PositiveIntegerField(null=False, blank=False, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) expiration_date = models.DateTimeField() user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE) updateAuction.html <form action="./updateData/{{ Auction.id }}" method="post" class="row w-25"> {% csrf_token %} Title: <input name="title" value="{{ Auction.title }}"> Description: <input name="description" value="{{ Auction.description }}"> Image: <input type="file" name="image" value="{{ Auction.cover }}"> Cost: <input type="number" pattern="[0-9]" min="0" name="lot_cost" onkeypress="return event.charCode >= 48 && event.charCode <= 57" value="{{ Auction.lot_cost }}"> Expiration date: <input type="date" name="expiration_date" value="{{ Auction.expiration_date }}"> <input type="submit" value="update" name="submit"> </form> -
[Django Rest Framework, try to call a specific header
I've got a view based on viewsets.ReadOnlyModelViewSet. All works fine when i call my API with my custom pagination. Now, I would like to implement a custom http header and call it with 'curl -I'. I know that is possible with Response(data, headers=[{'something': something}) Response documentation and : -->> https://github.com/encode/django-rest-framework/blob/22d206c1e0dbc03840c4d190f7eda537c0f2010a/rest_framework/mixins.py#L35 However, when i try to write my header like that, my custom pagination disapears. Is there a specific way to write headers with viewsets.ReadOnlyModelViewSet ? Thanks for reading me ! -
How to use API rest Framework for Images in Django
hello guys I am trying to create product model for my product details .i have some images for one product .i want to add multiple images in my django dashboard so i wrote this codes now i want show them in my template but i cant why? Here's my: Models.py : class Product(models.Model): name =models.CharField(max_length=100,verbose_name='نام محصول') header_pic = models.ImageField(upload_to="images/products",verbose_name='تصویر اصلی', default='images/product/product1.png') created_date =models.DateField(auto_now_add=True) description = RichTextField(blank = True , null=True) class Image(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE, related_name="product_images") image = models.ImageField(upload_to="images/products/product-images",verbose_name='تصویر', null= True , blank=True) @property def get_image_url(self): return self.image.url serializer.py : from django.db.models import fields from rest_framework import serializers from .models import Product, Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class ProductSerializer(serializers.HyperlinkedModelSerializer): images = serializers.SerializerMethodField() def get_images(self, product): return ImageSerializer(product.product_images.all(), many=True).data class Meta: model = Product fields = ('id','images') views.py : class ImageViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer admin.py from django.contrib import admin from .models import Product , ProductCategory ,Image from . import models admin.site.register(ProductCategory) class ImageAdmin(admin.StackedInline): model = models.Image extra = 4 @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ImageAdmin] readonly_fields=('views', ) class Meta: model = Product @admin.register(Image) class ImageAdmin(admin.ModelAdmin): pass template.html : <div class="product-bottom-slider owl-theme owl-carousel" id="sync2"> {% for img in images %} <div … -
How to show nested serializer data in parent table(Serializer) single list in python django rest framework
Country table that is grandparent table class Country(models.Model): country_id = models.IntegerField(primary_key=True) cname = models.CharField(max_length=100) def __str__(self): return self.name State table which is a direct child of the country class State(models.Model): stateid = models.IntegerField(primary_key=True) state_name= models.CharField(max_length=100) s_country = models.ForeignKey(Country, related_name='scountry', on_delete =models.CASCADE) def __str__(self): return self.state_name City table which is a direct child of State and indirect child of Country class City(models.Model): cityid= models.IntegerField(primary_key=True) city_name = models.CharField(max_length=100) city_strength = models.IntegerField() city_state = models.ForeignKey(State, related_name='cstate', on_delete =models.CASCADE) def __str__(self): return self.sname Serializers class StateSerializer(serialiizer.ModelSerializer): class Meta: model = State fields = '__all__' class CitySerializer(serialiizer.ModelSerializer): class Meta: model = City fields = '__all__' class FliterStateCitySerializer(serializers.ModelSerializer): state = StateSerializer(many=true) cities = CitySerializer(many=true) class Meta: model = Country fields = ('id', 'state', 'city') Views class FilterStateCityView(generics.ListAPIView): queryset = Country.objects.all() serializer_class = FliterStateCitySerializer The response I am getting is. [ { "country_id":"23", "cname": "USA", "state" : { "stateid": "16", "state_name": "Florida", "cities" : { "cityid":"55", "city_name": "Miami", "city_strength ": 40005 }, { "cityid":"56", "city_name": "Orlando", "city_strength ": 930067 }, }, { "stateid": "17", "state_name": "Texas", "s_country" : "USA" }, } ] Response that i want... [ { "country_id":"23", "stateid": "16", "cityid":"55", "state_name": "Florida", "city_name": "Miami", "city_strength ": 40005 }, { "country_id":"23", "stateid": "16", "cityid":"56", "state_name": "Florida", … -
TemplateDoesNotExist at /accounts/login/
I have checked the answers here, here, here, and here, and though I am getting the same error apparently I have a different root cause since those answers do not work for me. Here's the problem: I am using Django's LoginView, overriding the template name, but it only sometimes works. If I get to the login screen from the navbar, it works great, but the same url when gotten to from a different method throws a template does not exist error. My URLs file: from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = "accounts" urlpatterns = [ path( "login", auth_views.LoginView.as_view(template_name="accounts/login.html"), name="login", ), path("logout", auth_views.LogoutView.as_view(), name="logout"), path("signup", views.SignUp.as_view(), name="signup"), ] I have a nav item for the login screen, and it works great. The relevant section in the template: {% else %} <li class="nav-item"><a href="{% url 'groups:all' %}" class="nav-link">Groups</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:login' %}">Login</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:signup' %}">Sign Up</a></li> {% endif %} If someone clicks the login link in the navbar, it takes you to http://127.0.0.1:8000/accounts/login and works great. BUT: I have another section of code where you need to be logged in for a link to work, and … -
How to configure DB for Django, Celery, and SQS
I'm trying to offload a montecarlo task to Celery, and save the results to PostgreSQL AWS DB (RDS) from views.py: newResults = MonteCarloResultTrue.objects.create(htmlCompanyArray = "[]") viewRun = runMonteCarloAsync.delay(checkedCompaniesIDs,newResults.id) The object is created, but in tasks.py, the DB object is not being edited: @app.task(bind=True) def runMonteCarloAsync(self,checkedCompaniesIDs, calc_id): newResults = MonteCarloResultTrue.objects.get(id=calc_id) newResults.htmlCompanyArray = "[asdf]" newResults.save() How can I update the DB from the Celery task? Do I need to explicitly tell Celery where to look for the DB? (settings.py): CELERY_accept_content = ['application/json'] CELERY_task_serializer = 'json' CELERY_TASK_DEFAULT_QUEUE = 'django-queue-dev' CELERY_BROKER_URL = 'sqs://{0}:{1}@'.format( urllib.parse.quote(AWS_ACCESS_KEY_ID, safe=''), urllib.parse.quote(AWS_SECRET_ACCESS_KEY, safe='') ) CELERY_BROKER_TRANSPORT_OPTIONS = { "region": "us-east-1", 'polling_interval': 20 } CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' What am I missing? -
Single page application: How to prevent page reload when browser back button is clicked
I have a audio player in the base html file and I want it to continue playing when I navigate to other pages(home and playlist). It is working. But when I click the browser back button from the home or playlist page, the audio stops because the page reloads Note: I dont know how to post my codes here. I keep getting error