Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can't copy packages' info from virtual environment
idk why but this command doesn't work: pip freeze > requirements.txt the error is: The system cannot find the file specified but in fact, my terminal does create a file requirements.txt just doesn't copy the info about the used packages All the steps I followed: Activated venv created a github repo used git init created a .gitignore file used the above freeze command -
Bootstrap 5: Navbar Won't Expand when toggle clicked
I'm really new to bootstrap and HTML and when I use the HTML provided by bootstrap 5 for the search bar and toggler icon when the window is small, I'll see the toggler icon but it won't expand when clicked which is strange because it will on the example provided on bootstrap's website. This is my HTML file I'm using that has the navbar: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>Book Store</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand">Manga Book Store</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'home' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled">Disabled</a> </li> </ul> <div class="collapse navbar-collapse justify-content-center"> <form class="d-flex" role="search" method=POST action="{% url 'search_manga' %}"> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="Search … -
How do I create a timeseries line graph in django
I am making a website that displays the temperature in a room and I want to make a timeseries graph of the data. Within the HTML code displaying the page I want the graph on here is what I have: {% extends "dashboard/base.html" %} {% block content %} {% for Post in Posts %} <div> <h1>{{ Post.temperature }}</h1> <p1>{{ Post.timestamp }}</p1> </div> {% endfor %} {% endblock content %} So it currently displays a list of the Posts, showing their temperature and timestamp. I would like to turn this data into a timeseries graph. I have heard that you can do this using chart.js but this uses javascript and doesn't explain where to put the files. Any advice would be greatly appreciated -
Django admin inline conditioned on model field values
I'm trying to show one of three different child model inlines for a parent model, based on a selected field value within the parent model. I have tried every solution that pops up from various google searches but nothing seems to work. First a little background, I'm new to python and django but so far I feel that I have been a quick study. I'm attempting to build a web application to house information linked to various spatial locations. The geometry type (geom_type) for each location may be different (i.e., points, linestring, and polygons are possible). To capture this information I plan to create a parent model (Location) to house the name and geom_type (and possibly other metadata). The spatial data related to each Location would then be housed in three separate child models; one for each geom_type. When entering data I would like to create a new location and select the geom_type, which would then pull up the correct inline. Now for the details: Models from django.contrib.gis.db import models class Geometry(models.Model): TYPE = ( ('Point', 'Point'), ('Linestring', 'Linestring'), ('Polygon', 'Polygon'), ) geom_type = models.CharField('Geometry Type', choices = TYPE, max_length = 30) class Meta: verbose_name = 'Geometry' verbose_name_plural = 'Geometries' … -
Unexpected end of JSON
I have a django view for PUT method that returns JSON response as following: return JsonResponse({'foo':'bar'}, safe=False, status=204) When I fetch result from javascript and try to convert response to json using .then(response => response.json()) It gives error: Unexpected end of json input. -
Missing data from validated_data in django rest framwork
I'm building a web app and trying to send Post data as FormData to a Django Rest Framework Serializer. In the request.data I see that all the Post data is there, however after validating and saving the serializer it seems like some of the data did not get passed into validated_data. Views.py @api_view(["GET","POST"]) def api_list(request): if request.method=="GET": data = Recipe.objects.all() serializer = RecipeSerializer(data, many=True) return Response(serializer.data) elif request.method=="POST": print("POST recieved") print (request.data) <----See below serializer = RecipeSerializer(data=request.data) print("Validating..") if serializer.is_valid(): print("validated!") serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) print (serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) request.data <QueryDict: {'description': ['"gfdgdfg"'], 'name': ['"fdgdfgdf"'], 'ingredients': [ '{"name":"dfgdfg","amount":"gdfgd"}', '{"name":"fdgdfg","amount":"dfgdf"}', '{"name":"dfgdfgdf","amount":"gdfgdf"}' ], 'directions': [ '{"content":"gdfgfd"}', '{"content":"gdfgdfg"}', '{"content":"dfgdfdfg"}' ], 'image': [ <InMemoryUploadedFile: luisana-zerpa-MJPr6nOdppw-unsplash.jpg (image/jpeg)> ] }> serializer.py class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = ('name', 'amount') class DirectionSerializer(serializers.ModelSerializer): class Meta: model = Direction fields = ('content',) class RecipeSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField() ingredients = IngredientSerializer(many=True, read_only=False) directions = DirectionSerializer(many=True, read_only=False) class Meta: model = Recipe fields = ( 'id', 'name', 'owner', 'image', 'description', 'created_at', 'ingredients', 'directions', ) def create(self, validated_data): print (validated_data) <----See Below has_ingredients = validated_data.get("ingredients") has_directions = validated_data.get("directions") if has_ingredients: ingredient_data = validated_data.pop('ingredients') if has_directions: direction_data = validated_data.pop('directions') recipe_name = validated_data.get('name') recipe_name = recipe_name.replace('"','') recipe_description = validated_data.get('description') recipe_description … -
Fill my database as I go with data from an API - Django Prject
I would like to fill my database as I go with data from an API that I use that sends me data users. Here when a user already exists and we just modify his information at the API level, then I would just like to apply the modify the information not duplicate the user, and if he does not exist in my database I will create. But every time I call the API, if the user already existed in my database, it creates it again (duplicate) and I don't want this side Note that I retrieve user data in the form of a dictionary Please where is the problem views.py from .models import Utilisateur url='http://userAPI/Users/GetUsers' y=requests.get(url) users=y.json() all_users=users['user'] for one_user in all_users: user=Utilisateur(name=one_user['name'],adresse=one_user['adresse'],code=one_user['code']) user.save() models.py from django.db import models class Utilisateur(models.Model): name=models.CharField(max_length=100) adresse=models.CharField(max_length=255,blank=True,null=True) code=models.CharField(max_length=10) -
When using Generics types and ModelSerializer, how can I Serialize an Inherited class instead of the Base class in Django Rest Framework?
Context: models.py Let's say I have a Generic Django Model class called "Base" to group all other classes that extend it: class Base(models.Model): name = models.CharField(...) belongs_to = models.ForeignKey( 'self', on_delete=models.PROTECT, blank=True, null=True ) And the class "Company", that extends the "Base": class Company(Base) pass # It just extends the Base Attributes. The class "Manager", also extends "Base" but it has a role attribute: class Manager(Base) role = models.ForeignKey(Roles, on_delete=models.CASCADE ...) And the class "Worker", that also extends "Base" but it has a job attribute: class Worker(Base): job = models.ForeignKey(Jobs, on_delete=models.CASCADE ...) Implementation Here's an example of how they can be instantiated: Company.objects.create(name='Company1', belongs_to=None) # This will also create a Base Object with the ID 1. Manager.objects.create(name='Manager1', belongs_to=1 [[company]], role=1) # This will create a Manager object and relate it to the Company. # (And also create a Company object with the ID 2, that don't make much sense, but is only an abstract example) Worker.objects.create(name='Worker1', belongs_to=2 [[manager]], job=1) # In this case, I'm saying that the Worker is grouped under the Manager Object. The Idea is that, the Worker can also not have a manager and be directly related under a Company, like: (...) Worker.objects.create(name='Worker34', belongs_to=1 [[company]], job=1) # … -
What are the caching methods using rabbitmq in Django?
I am Django developer and I know about Redis caching method and technique. But my project is big, and I develop the project in RabbitMQ with celery. I want to put some caching technique to make my project fast. Can anyone help me find some good website or tell me stuff like Redis default caching? I am using Django, celery, RabbitMQ, nginx and Postgres database. -
Cannot assign "'75f37671bac8'": "Results.prescription" must be a "Prescription" instance
I'm trying to add a patient to my result form, but it says Cannot assign "'75f37671bac8'": "Results.prescription" must be a "Prescription" instance. Models.py class Patient(models.Model): uniqueId = models.CharField(null=True, blank=True, max_length=100) slug = models.SlugField(max_length=500, unique=True, blank=True, null=True) date_created = models.DateTimeField(blank=True, null=True) last_updated = models.DateTimeField(blank=True, null=True) class Results(models.Model): title = models.CharField(null=True, blank=True, max_length=100) number = models.CharField(null=True, blank=True, max_length=100) dueDate = models.DateField(null=True, blank=True) status = models.CharField(choices=STATUS, default='CURRENT', max_length=100) notes = models.TextField(null=True, blank=True) #RELATED fields patient = models.ForeignKey(Patient, blank=True, null=True, on_delete=models.SET_NULL) views.py if request.method == 'POST': doc_form = DoctorForm(request.POST) inv_form = ResultsForm(request.POST, instance=results) patients_form = PatientSelectForm(request.POST, initial_patient=results.patient, instance=results) if doc_form.is_valid(): obj = doc_form.save(commit=False) obj.results = results obj.save() messages.success(request, "Results Doctor added succesfully") return redirect('create-build-results', slug=slug) elif inv_form.is_valid and 'paymentTerms' in request.POST: inv_form.save() messages.success(request, "Results updated succesfully") return redirect('create-build-results', slug=slug) elif patients_form.is_valid() and 'patient' in request.POST: patients_form.save() messages.success(request, "Client added to Results succesfully") return redirect('create-build-results', slug=slug) traceback line elif patients_form.is_valid() and 'patient' in request.POST: -
How do I add custom error messages in the Django Rest Framework API Key library?
I have implemented the Django Rest Framework API Key library for Authentication in my project and it is working well, however I noticed that "403 Forbidden" with { "detail": "Authentication credentials were not provided" } is given whenever there is any issue. For example, if the key has expired then these details are given, if the key has been provided but is invalid then these details are given, and so on. I want to be able to tell the client what exactly is wrong - because for an expired key: "credentials were not provided" is not correct - because credentials were provided, it's just that they're expired! Is this possible - or even safe to do? This is the library: https://florimondmanca.github.io/djangorestframework-api-key/ -
The CreateView page doesn't take into account the form
I tried to create in Django an create view , to use form and it doesn't work. The program doesn't use form. I don t understand why the form doesn t work. urls.py from django.urls import path from .views import ( ItemListView, ItemDetailView, ItemCreateView ) urlpatterns = [ path(r'', ItemListView.as_view(template_name='item_list.html'), name='ListView'), path(r'create/', ItemCreateView.as_view(), name='create'), path(r'<int:pk>/', ItemDetailView.as_view(), name='s'), ] models.py class Item(models.Model): #associations user =models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) article =models.ForeignKey(Article, on_delete=models.CASCADE) #item stuff name =models.CharField(max_length=120) description =models.TextField(blank=True, null=True, help_text='Separate each item by comma') exceptions =models.TextField(blank=True, null=True, help_text='Separate each item by comma') bl =models.BooleanField(default=True) timestamp =models.DateTimeField(auto_now_add=True) updated =models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('menus:s', kwargs={'pk':self.pk}) class Meta: ordering = ['-updated','-timestamp'] def get_description(self): return self.description.split(',') def get_exceptions(self): return self.exceptions.split(',') views.py class ItemCreateView(CreateView): template_name = 'menus/form.html' form_class = ItemForm def get_queryset(self): return Item.objects.filter(user=self.request.user) def get_context_data(self,*args, **kwargs): context=super(ItemCreateView, self).get_context_data(**kwargs) title='Add Item' context={ 'title' : title } def form_valid(self, form): instance = form.save(commit=False) instance.user = self.request.user return super(ItemCreateView, self).form_valid(form) forms.py from django import forms from .models import Item class ItemForm(forms.ModelForm): class Meta: model = Item fields = [ 'name', 'description', 'exceptions', 'bl', ] form.html {% extends 'main\base.html' %} {% block content %} <html> <body> <p>{{ title }}</p> {% if form.errors.non_field_errors %}{{ form.errors.non_field_errors }}{%endif%} <form method="POST"> {% csrf_token %} {{ form.as_p … -
Add Content-Disposition header to drf-yasg
I have a django APIView with swagger documentation using drf-yasg. Anytime I make a post request to the API i get this error response { "detail": "Missing filename. Request should include a Content-Disposition header with a filename parameter." } When I add the Content-Disposition header to the postman request it I am able to get the right responses. Content-Disposition: attachment; filename=<insert-your-file-name> My question is how do I add the Content-Disposition to the drf-yasg swagger_auto_schema decorator if possible. This is how my APIView looks like class ReceiptsUploadView(APIView): parser_classes = (FileUploadParser, MultiPartParser) params = [openapi.Parameter("file", openapi.IN_FORM, type=openapi.TYPE_FILE)] @swagger_auto_schema(operation_description="file", manual_parameters=params) def post(self, request): file_obj = request.FILES.get("file") if file_obj: fs = FileSystemStorage() file = fs.save(file_obj.name, file_obj) file_url = os.path.join(settings.BASE_DIR, fs.url(file)[1:]) receipt_blocks = Receipt(blocks=extraction_data(file_url)) receipt_blocks.save() return Response( extraction_data(file_url), status=status.HTTP_200_OK, ) else: return Response( {"error": "file not selected"}, status=status.HTTP_400_BAD_REQUEST ) -
Django Graphene Custom Error not showing extensions
I am using graphene_django and I am interested in having custom errors being raised What I am trying is: class CustomGraphQLError(GraphQLError): def __init__(self, message, extensions, nodes=None, source=None, positions=None, path=None, original_error=None): super().__init__(message, nodes, source, positions, path, original_error, extensions) and then raising an error like this raise CustomGraphQLError Despite I have made extensions mandatory, they don't seem to appear in the response Example response { "errors": [ { "message": "Custom error", "locations": [ { "line": 2, "column": 3 } ], "path": [ "traces" ] } ], "data": { "traces": null } } Can't understand whats wrong here -
How to divide Daphne requests on mutiple processors?
I use a Daphne server for my ASGI Django application. When I run htop on my Ubuntu server it shows all the load on only one processor and the app gets slow, so I'd like to know what is the easiest way to speed up my server. App is inside a Docker container. I run Daphne with command: daphne WBT.asgi:application --bind "0.0.0.0" --port "8000". I use Nginx as a proxy. I tried using uvicorn server with multiple workers but then I get problems with layout. Ie. let's say that I have 4 workers when I visit my web app, it loads it on only one worker correctly, so in 25% cases I get no layout. -
Django restframework-simple-jwt: Could not deserialize key data
I'm trying to use django-simplejwt & restframework with RSA256. I generated my keypair by following this gist. The public & private keypair are being saved in a .env file: JWT_SIGNING_KEY='-----BEGIN RSA PRIVATE KEY-----\\n keydata\\n -----END RSA PRIVATE KEY-----' JWT_VERIFYING_KEY='-----BEGIN PUBLIC KEY-----\\n keydata\\n -----END PUBLIC KEY-----' My jwt configuration settings.py looks like this (additional info is for compatibility with Auth0): REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } SIGNING_KEY = os.getenv("JWT_SIGNING_KEY") VERIFYING_KEY = os.getenv("VERIFYING_KEY") SIMPLE_JWT = { 'USER_ID_FIELD': 'user_id', 'ACCESS_TOKEN_LIFETIME': timezone.timedelta(minutes=10), 'REFRESH_TOKEN_LIFETIME': timezone.timedelta(hours=6), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM' : 'RS256', # Default would be HS256 'SIGNING_KEY' : f'''{SIGNING_KEY}''', #config("JWT_SIGNING_KEY"), # Must be private key 'VERIFYING_KEY' : f'''{VERIFYING_KEY}''', #config("JWT_VERIFYING_KEY"), # Must be public key 'AUDIENCE' : config("JWT_AUDIENCE"), 'ISSUER': config("JWT_ISSUER"), 'JWK_URL': f'{config("JWT_ISSUER")}/.well-known/jwks.json', 'USER_ID_CLAIM': f'{config("JWT_AUDIENCE")}/email', 'JTI_CLAIM': None, 'TOKEN_TYPE_CLAIM': None, 'AUTH_HEADER_TYPES': ('Bearer',), } When restricted views that need a user object are being called, a function for decoding the jwt token and returning the corresponding user object is being executed: def token_user(request): s, token = request.META["HTTP_AUTHORIZATION"].split(" ") decoded = jwt.decode(token, settings.VERIFYING_KEY, algorithms=["RSA256"]) username = decoded["username"] user = get_user_model().objects.filter(username=username) return user Here are my Login view & LoginSerializer (I cut out most of the validation process since this worked before implementing jwt. … -
How does set_group_by works in Django?
I was writing the following query: claim_query = ClaimBillSum.objects.filter(claim__lob__in = lobObj)\ .annotate(claim_count = Count("claim__claim_id", distinct=True))\ .annotate(claim_bill_sum = Sum("bill_sum"))\ .values("claim__body_part", "claim_count", "claim_bill_sum")\ .order_by("claim__body_part") When I checked the query property, it was grouped by all properties of the tables related in this query, not only the ones selected in the values() function, when I only wanted to group by claim__body_part. As I searched for a way to change the group by instruction, I found the query.set_group_by() function, that when applied, fixed the query in the way I wanted: claim_query.query.set_group_by() SELECT "CLAIM"."body_part", COUNT(DISTINCT "claim_bill_sum"."claim_id") AS "claim_count", SUM("claim_bill_sum"."bill_sum") AS "claim_bill_sum" FROM "claim_bill_sum" INNER JOIN "CLAIM" ON ("claim_bill_sum"."claim_id" = "CLAIM"."claim_id") WHERE "CLAIM"."lob_id" IN (SELECT U0."lob_id" FROM "LOB" U0 WHERE U0."client_id" = 1) GROUP BY "CLAIM"."body_part" ORDER BY "CLAIM"."body_part" ASC But I couldn't find any information in Django documentation or anywhere else to better describe how this function works. Why the default group by is selecting all properties, and how .set_group_by() works, selecting exactly the property I wanted? -
NoReverseMatch: Reverse for 'account_confirm_email' not found. [dj-rest-auth]
I am new to Django. I'm trying to implement jet authentication along with social authentication. I'm following this tutorial https://jkaylight.medium.com/django-rest-framework-authentication-with-dj-rest-auth-4d5e606cde4d I tried to implement the same but its not working. I'm getting this error: django.urls.exceptions.NoReverseMatch: Reverse for 'account_confirm_email' not found. 'account_confirm_email' is not a valid view function or pattern name. My project level urls.py from drf_spectacular.views import ( SpectacularAPIView, SpectacularSwaggerView ) from django.contrib import admin from django.urls import path, include urlpatterns = [ # path('account/', include('allauth.urls')), path('admin/', admin.site.urls), path('api/user/', include('user.urls')), path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'), path( 'api/docs/', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs' ), ] My App level urls.py from django.urls import path, re_path from dj_rest_auth.registration.views import RegisterView, VerifyEmailView, ConfirmEmailView from dj_rest_auth.views import LoginView, LogoutView from user import views app_name = 'user' urlpatterns = [ path('account-confirm-email/<str:key>/', ConfirmEmailView.as_view()), path('register/', RegisterView.as_view()), path('login/', LoginView.as_view()), path('logout/', LogoutView.as_view()), path('verify-email/', VerifyEmailView.as_view(), name='rest_verify_email'), path('account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), path('listusers/', views.ListUsers.as_view(), name='list-users'), ] When I try to register a user. It causes this error. I'm using dj-rest-auth package to implement authentication. -
how to solve unusual logical error in django
So I made this transaction process that will pass with the help of phone number. But the logic is not working properly. sender side is deducting way more numbers that i want to send. for example, if i want to send 100, it's deducting 500 and receiver is not receiving the amount. can anyone help me with this? models.py class extenduser(models.Model): ID= models.IntegerField(null=True, default=None) FirstName= models.CharField(max_length= 50) MiddleName= models.CharField(max_length=50) LastName= models.CharField(max_length=50) phone= models.CharField(max_length=20) user= models.OneToOneField(User, on_delete=models.CASCADE) class Status (models.Model): user_name = models.CharField(max_length=150, default=None) account_number = models.IntegerField() balance = models.IntegerField() phone_number= models.CharField(max_length=20,default=None) class MoneyTransfer(models.Model): enter_your_user_name = models.CharField(max_length = 150, default = None) enter_the_destination_account_number = models.IntegerField() enter_the_destination_phone_number=models.CharField(max_length=20, default=None) enter_the_amount_to_be_transferred_in_INR = models.IntegerField() views.py def randomGen(): # return a 6 digit random number return int(random.uniform(100000, 999999)) def index(request): try: curr_user = Status.objects.get(user_name=request.user) # getting details of current user except: # if no details exist (new user), create new details curr_user = Status() curr_user.account_number = randomGen() # random account number for every new user curr_user.balance = 0 curr_user.user_name = request.user curr_user.phone_number= extenduser.phone curr_user.save() return render(request, "epayapp/index.html", {"curr_user": curr_user}) def TransferMoney(request): if request.method == "POST": form = forms.MoneyTransferForm(request.POST) if form.is_valid(): form.save() curr_user = models.MoneyTransfer.objects.filter(enter_your_user_name=request.user).first() dest_user_acc_num = curr_user.enter_the_destination_account_number dest_phone_num= curr_user.enter_the_destination_phone_number temp = curr_user # NOTE: Delete this … -
How do I create a cookiecutter project for Django 4.x instead of the default 3.x?
I want to start a new django project with cookiecutter and would like to leverage the Django 4.0+ for it. Is this supported with cookiecutter, or is there a reliable workaround for it? -
django nested Prefetch with to_attr not working
so i have this kind of queryset: prods = Product.objects.prefetch_related( Prefetch( 'packs', queryset=Pack.objects.all(), to_attr='my_packs'), Prefetch( 'packs__orders', queryset=Order.objects.all(), to_attr='my_orders') ) pack has a foreign key to product, and pack with order has a m2m relation. so this prods[0].my_packs works. but there is no attribute called my_orders in my qs -> prods[0].my_orders why does this happen? and how can i make this work? -
django objects.create method is too slow How to make faster?
multiple tables are mapped and, when I create post request, it takes about 2~3 seconds. Is there any ways to fix it? I guess it takes a long time on: objects.create for loop product.objects.get however, I am not able to find the better ways.. models: #product, Order, OrderItems, ShippingAddress are mapped class Order(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) order_date = models.DateTimeField(auto_now=True) is_paid = models.BooleanField(default=False) paid_at = models.DateTimeField(auto_now=False, null=True, blank=True) delivery_code = models.CharField(max_length=255, null=True, blank=True) is_delivered = models.BooleanField(default=False) delivered_date = models.DateTimeField(auto_now=False, null=True, blank=True) total_price = models.DecimalField(max_digits=7, decimal_places=2, null=True) shipping_price = models.DecimalField(max_digits=7, decimal_places=2, null=True) payment_method = models.CharField(max_length=255,null=True) def __str__(self): return str(self.user) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete= models.CASCADE, null=True, blank=True) product = models.ForeignKey(Product, on_delete= models.CASCADE) name = models.CharField(max_length=200, null=True) image = models.CharField(max_length=255, null=True) qty = models.IntegerField(default=0, null=True) price = models.DecimalField(max_digits=7, decimal_places=2, null=True) def image_preview(self): if self.image: return mark_safe('<img src="{0}" width="55" height="55" />'.format(self.image)) else: return '(No image)' def __str__(self): return str(self.product) class ShippingAddress(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) order = models.OneToOneField(Order, on_delete=models.CASCADE, null=True, blank=True) address = models.CharField(max_length=255, null=False) city = models.CharField(max_length=255, null=False) postal_code = models.CharField(max_length=255, null=False) country = models.CharField(max_length=255, null=False) def __str__(self): return str(self.user) view: @permission_classes(IsAuthenticated) @api_view(['POST']) def OrderCreate(request): data = request.data user = request.user order_items = data['orderItems'] #1.create order order = Order.objects.create( user … -
Django serializers.save() does not use postgres
I have the following function that runs automatically with cronjob, it makes predictions based on an anomaly detection model and it saves the results to a postgres database: def prediction_job(): """ This job will run once every batch_minutes minutes to predict if the IPs appear in these batch_minutes minutes are normal or malicious and save the results to postgres """ ip_estimator = IpStatePrediction() predictions = ip_estimator.predict_ip_state() predictions_dict_final = convert_dict_for_serializer(predictions) serializer_result = PredictionsSerializer(data=predictions_dict_final) if serializer_result.is_valid(): serializer_result.save() else: logger.debug("Error with data {}.".format(serializer_result.errors)) When I run it locally after running the commands python3 manage.py runserver and python3 migrate --database postgres, it saves the results to postgres. However on production I am getting the following error, when the function is executed: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: unrecognized token: ":" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 108, in debug_sql yield File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File … -
module 'django.contrib.admin' has no attribute 'action' this code is copied from the docs
from django.contrib import admin from .models import Post @admin.action(description="Publish selected Posts") def make_publish(modeladmin,request,queryset): queryset.update(status="published") -
Django FileField reading big CSV files effectively
Lets say that I have model that contains csv files: class MyModel: my_file = model.FileField(...) I can read my csv file data like this right now: import csv csv_data = self.my_file.read().decode('utf-8') reader = csv.reader(csv_data.splitlines()) However this method is not effective. It literally loads whole file into memory and tries to work with them. My CSV files are very big (more than 100MB) and they are hosted on S3 service. Is there any effective way to parse CSV data?