Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateSyntaxError: Could not parse the remainder: '${id}' from '${id}'
I am trying to pass javascript variables into the URL template in my ajax call within my script tag but it keeps telling me that it could not parse the remainder. Any idea how it should be? $.ajax({ type: 'POST', url: `{% url 'posts:toggle-reaction' object_id=${id} object_type=${type} %}`, data: serializedData, success: function (response) { }, error: function (response) { // alert the error if any error occured alert(response["responseJSON"]["error"]); } }) -
Site matching query does not exist even. Everything is set, site domain defined
So i just want my sitemap.xml to work in production. I have included this module in INSTALLED_APPS: 'django.contrib.sites', I have declared SITE_ID: SITE_ID = 1 I defined domain name 'mydomain.com' in sites model which is exacly the domain my site running on. I restarted the server And i still get 'django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist' error I don't get this error when i run on localhost. -
django.core.exceptions.ImproperlyConfigured after using reverse()
I'm new in Django. Here is my issue. I'm trying to use reverse() function to add 'data-url' attribute to my form in my forms.py file in order to use it in my JavaScript then. But I run into the following exceptions: django.core.exceptions.ImproperlyConfigured: The included URLconf 'orthodontist.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import The thing is reverse() with the same url name works fine in my view.py file. Here is my code: forms.py class OrderByForm(forms.Form): order_by = forms.ChoiceField(required=False, choices=ORDER_BY, label='Сортировать по', widget=forms.Select(attrs={ 'class': 'form-control', 'data-url': reverse('ask:question_ajax') })) project urls from django.contrib import admin from django.urls import path, include from index import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index), path('signup/', views.signup, name='signup'), path('login/', views.login_view, name='login'), path('logout/', views.logout_view, name='logout'), path('user/<int:pk>/', views.UserView.as_view(), name='user'), path('user/<int:pk>/popular/', views.UserViewPopular.as_view(), name='user_popular'), path('user/<int:pk>/update/', views.UserViewUpdate.as_view(), name='update'), # path('user/<int:pk>/update_post', views.user_update_post, name='update_post'), path('admin/', admin.site.urls), path('search/', views.SearchResults.as_view(), name='search'), path('question/', include('ask.urls')), ] if bool(settings.DEBUG): urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app urls from django.urls import path from . import views app_name = 'ask' urlpatterns = [ path('', views.AskView.as_view(), name='index'), path('<int:pk>/', views.QuestionDetail.as_view(), name='question'), path('ask/', views.AskQuestionView.as_view(), name='ask_question'), path('<int:pk>/delete_question/', views.delete_question, name='delete_question'), path('<int:pk>/delete_answer/', … -
Custom @property used as APIField is displayed correctly but can't be used for ordering the results
I have a model for a Normal Wagtail page, which has two fields, and a custom property like this: class DetailPage(AbstractSitePage): total = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) additional_amount = models.DecimalField( max_digits=12, decimal_places=2, null=True, blank=True, default=Decimal("0.00") ) content_panels = [ FieldPanel("additional_amount"), ] + AbstractSitePage.content_panels api_fields = [ APIField("additional_amount"), APIField("total"), APIField("new_total") ] class Meta: ordering = ("-total",) @property def new_total(self): if self.additional_amount: return str(self.total + self.additional_amount) return str(self.total) doing so makes the following URL works just fine and displays the new_total values correctly /api/v2/pages/?type=sitepages.DetailPage&fields=additional_amount,new_total&order=-total but if I try to order with the new_total property /api/v2/pages/?type=sitepages.DetailPage&fields=additional_amount,new_total&order=-new_total isn't it supposed to work since it's already displayed and computed correctly?? and what can I do about this? -
Django wrong directories
My project has a core/template folder to place submit.html. I need to display some images. My project structure is like bellow: myproject static/images (my images) core/template (html files) I've also tryied core/template/images (jpg or png files) I've put some commands like these in settings file STATIC_URL = '/static/' MEDIA_URL = 'templates/images/' But it won't show up on submit.html page. I've tryied 3 ways for showing images but none will show them. This is what my terminal shows [21/Apr/2021 05:48:34] "POST /submit HTTP/1.1" 200 1054 [21/Apr/2021 05:48:34] "GET /static/images/coxinha.jpg HTTP/1.1" 404 1682 [21/Apr/2021 05:48:34] "GET /static/images/mini_coxinha.jpg HTTP/1.1" 404 1697 Not Found: /images/coxinha.png [21/Apr/2021 05:48:34] "GET /images/coxinha.png HTTP/1.1" 404 2230 -
Django problems loading static files
I am trying to add external JS file to my Django project. Unfortunately it doesn't work while I am trying to add it in many ways: In my template.html I have specified direct path: {% load static %} < script> src="{% static 'commerce/static/js/test.js' %}" < /script> it doesn't work. My settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] my layout.hmtl: {% load static %} <script src="{% static 'js/test.js' %}"></script> Depending on sources combination, I receive various output in terminal regarding status of loaded files: "GET / HTTP/1.1" 200 5167 "GET /static/js/test.js HTTP/1.1" 304 0 "GET / HTTP/1.1" 200 5167 "GET /static/js/test.js HTTP/1.1" 200 0 "GET / HTTP/1.1" 200 5167 "GET /static/js/test.js HTTP/1.1" 404 0 Even if my 'test.js' is loaded correctly (HTTP status 200 or sometimes no information regarding test.js load status), my javascript functions doesn't work. In order to check if other static files are loaded I even tried to remove my CSS file from static folder and surprisingly (or not), after re-running my app it is still formatted. Although I left source for CSS unchanged in my layout.html: {% load static %} <link href="{% static 'css/styles.css' %}" rel="stylesheet"> Summarizing: I cannot manage … -
Django: No ReverseMatch. How to reverse to the previous URL?
I have a model class Client and the URL for this model object is <local_server>/object_id/ Where object_id is the id of the object of model Client. Now, when I am at this URL, there is a button on the page called Add Installment to add the installment for that particular Client. When I click on this button it takes me to the following URL: <local_server>/object_id/add_installment Now if I add the new installment, it works fine. But the Add Installment page has two buttons, Add and Cancel. I want that If I click on Cancel it should get back to the following URL: <local_server>/object_id/ And for that I have the following template for adding installment, where you can see the Cancel button. installment_form.html {% extends "client_management_system/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content_section"> <form method="post"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Add New Installment</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-success" type="submit">Add Installment</button> <a class="btn btn-outline-danger" type = "submit" href="{% url 'client_details' object.id %}" >Cancel</a> </div> </form> </div> {% endblock %} In the Cancel button, client_details is the name of the URL <local_server>/object_id. I have written the object.id in that line, but when … -
Django only accepts base URL after deployed but not on local machine
My django URLs work just fine on local development, but only the base URL works deployed on a godaddy server. I'm running the django application through the cPanel Python Web Applications on Python 3.7.8 I know django is working and my code reaches a method in my views.py file when the URL is just www.mysite.com, for example wwww.mysite.com/page would yield a 500 error Views.py def index(request, *args, **kwargs): print("views.py in index()", request) return render(request, 'index.html') I use this method to route URLs through a react app I have, all of which works on local development. urls.py file for the project from django.contrib import admin from django.urls import path, include, re_path from django.conf.urls import url, include from rest_framework import routers from app import views from rest_framework_jwt.views import obtain_jwt_token from rest_framework_jwt.views import refresh_jwt_token from rest_framework_jwt.views import verify_jwt_token from django.views.generic import TemplateView router = routers.DefaultRouter() router.register(r'app', views.SessionView, 'app') router.register(r'project', views.ProjectView, 'project') urlpatterns = [ path('admin/', admin.site.urls), path('token-auth/', obtain_jwt_token), url(r'token-renew/', refresh_jwt_token), url(r'token-verify/', verify_jwt_token), path('api/', include(router.urls)), path(r'', include('app.urls')), path('', TemplateView.as_view(template_name = 'index.html')), #re_path('.*', TemplateView.as_view(template_name = 'index.html')), ] urls.py file for the app from .views import current_user, UserList, index from django.conf.urls import url from app import views urlpatterns = [ url(r'ViewSession/(?P<pk>[0-9]+)', index), path('ViewSessions', index), url(r'ViewProject/(?P<pk>[0-9]+)', index), … -
React JS: problem in receiving cookie with axios, which is received from JWT Django
First of all, I had made a POST APIView function using Django and added JWT token in it. This api is basically made for the login purpose. I can transfer all the details in it and recieve a cookie in return. class LoginView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('user not found') if not user.check_password(password): raise AuthenticationFailed('Incorrect password') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = { 'jwt': token } return response I used POST request using axios in react js and trying to recieve cookie too with the help of "withCredentials: true" yet unable to get the cookie. import React, { Component } from 'react'; import axios from 'axios'; class Login extends Component { state = { email: '', password: '', }; handleSubmit(event){ event.preventDefault(); axios({ method: 'post', url: 'http://127.0.0.1:8000/user/login ', withCredentials: true, data: { email: this.state.email, password: this.state.password } }) .then(data => console.log(data)); } handleChange(event){ const target = event.target; const value = target.value; const name = target.name; this.setState({[name]:value}) } render() { return ( <div> <h1>LOGIN</h1> <form onSubmit={this.handleSubmit.bind(this)}> <div> <label>Email: </label> <br … -
How to upload multiple images in a django model WITHOUT using a form?
I'm tryign to upload multiple images in a django model WITHOUT usign forms. I need to "populate" my db with images so I can show them in my frontend. These images are storage in a folder inside my project but I couldn't find a way to send them to my model. Any ideas about how I can make it? -
How to pre-populate django forms at CreateView
how can i prepopulate fields in django forms at create an instance with the fields from my profile model. say if my Profile model has a Charfield residence and in the registration i named a certain user's residence as say 'Cairo', I would like to know how i can go to fill in a form say a PostCreateForm and have the residence of a user get auto filled with Cairo and also make it non-editable. Such that if a form is asking for Post body and residence of the owner of the post, this logged in user will be able to just enter the post body details and at the post details view, he can view his posts with his residence attached to them. I have tried implementing the form = PostForm(initial={"residence": "Cairo"}) kind of approach as per the documentation but i'm still getting it wrong. I tried it in my Views and in my form definition but seems i did it wrong. I need help on how i can implement this on the get requests of the CreateView or in the forms.py model definition. Any help will be greatly appreciated. -
Django Rest Framework Filtering an object in get_queryset method
Basically, I have a catalog viewset. In the list view I want to make a few filtering and return accordingly. Relevant Catalog model fields are: class Catalog(models.Model): name = models.CharField(max_length=191, null=True, blank=False) ... team = models.ForeignKey(Team, on_delete=models.CASCADE, editable=False, related_name='catalogs') whitelist_users = models.JSONField(null=True, blank=True, default=list) # If white list is null, it is open to whole team Views.py class CatalogViewSet(viewsets.ModelViewSet): permission_classes = (IsOwnerAdminOrRestricted,) def get_queryset(self): result = [] user = self.request.user catalogs = Catalog.objects.filter(team__in=self.request.user.team_set.all()) for catalog in catalogs: if catalog.whitelist_users == [] or catalog.whitelist_users == None: # catalog is open to whole team result.append(catalog) else: # catalog is private if user in catalog.whitelist_users: result.append(catalog) return result So this is my logic; 1 - Get the catalog object if catalog's team is one of the current user' team. 2 - Check if the catalog.whitelist_users contains the current user. (There is also an exception that if it is none means it s open to whole team so I can show it in the list view.) Now this worked but since I am returning an array, it doesn't find the detail objects correctly. I mean /catalog/ID doesn't work correctly. I am new to DRF so I am guessing there is something wrong here. How … -
Django prevent run command dbbackup invoke other command
I got a Django server and I want to backup the database everyday(using sqlite3), so I install django-dbbackup to do the job. I also install the django-apscheduler to do some scheduler task. So I got a command file runscheduler.py which I call from start of the views.py using other thread with management.call_command. When I test dbbackup python manage.py dbbackup in CMD Prompt, the backup command invoke the scheduler . How can I prevent that? -
Django Rest Framework - Account Verification Email: send_mail() works in console but not using SMTP
I have looked around StackOverflow and other places but I am not able to find a solution to my problem. I am using Django Rest Framework and Django Knox for user authentication and I want to send an account verification email to newly registered users. I am using Gmail. My email settings in my settings.py file are as below: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' #Using this for testing EMAIL_USE_TLS = True EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_PORT = os.getenv('EMAIL_HOST_PORT') EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') DEFAULT_FROM_EMAIL = os.getenv('EMAIL_HOST_USER') When I use EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend', I am able to see the email printed on the server. However when I use EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend', I don't get the email every time. I have to try sending an email multiple times to receive 1 email. Because I am receiving emails a few times, I think my credentials are right. I don't see any errors printed on the server either. Is this a Gmail issue considering I am receiving emails sometimes? An additional thing I noticed while working on this was that any code after send_mail is not executed in my API view. I am using a custom user model and my Register API … -
Could not parse remainder error while using ternary operator?
users.html <td><div class="form-group"> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="user-{{i.id}}" {{(i.status) ? 'checked' : ' '}} onclick="changeUserStatus(event.target, {{ i.id }});"> <label class="custom-control-label pointer"></label> </div> </div> </td> why this error is showing? Could not parse the remainder: '(i.status=='True') ? 'checked' : ''' from '(i.status=='True') ? 'checked' : ''' any help will be appreciated? -
Django Nested Serializer Error: "The serializer field might be named incorrectly and not match any attribute or key"
I'm trying to get a json out similar to this: { name: Barry Bonds, playerListing: { best_buy_price: 69,420 } } Here is the serializer.py. class PlayerListingForProfileSerializer(serializers.ModelSerializer): class Meta: model = PlayerListing fields = ( 'best_buy_price', ) class PlayerProfileSerializer(serializers.ModelSerializer): PlayerListingField = PlayerListingForProfileSerializer() class Meta: model = PlayerProfile fields = ( 'PlayerListingField', 'card_id', 'name', ) Here is the model.py: class PlayerProfile(models.Model): card_id = models.CharField(max_length=120, unique=True, primary_key=True) name = models.CharField(max_length=120, null=True) class PlayerListing(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, #db_constraint=False null=True) name = models.CharField(max_length=120, null=True) best_buy_price = models.IntegerField(null=True) I've had this working before but I can't figure out why it's throwing the error this time; Got AttributeError when attempting to get a value for field `PlayerListingField` on serializer `PlayerProfileSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `PlayerProfile` instance. Original exception text was: 'PlayerProfile' object has no attribute 'PlayerListingField'. -
Get API result when sending SparkPost email from Django?
Django has built-in support for sending mail via sparkpost, if you set MAIL_BACKEND in settings.py: EMAIL_BACKEND = 'sparkpost.django.email_backend.SparkPostEmailBackend' SPARKPOST_API_KEY = 'something' Once it's set up, you can use the standard Django ways to send mail (the send_mail() function or the EmailMessage class). If I send a message via the SparkPost API directly, it returns a result that looks like this: {'total_rejected_recipients': 0, 'total_accepted_recipients': 1, 'id': '1234567890'} Does Django offer a way to access this API result? -
Git file problem when migrating in Django
I have the following structure in my Django project The gitignore is the one suggested by https://www.toptal.com/developers/gitignore/api/django The steps to initialize GIT were: Create the project with apps/A and apps/B, create the .gitignore file and run git init. Then I ran makemigrations and migrate The problem occurs when, starting from master, a new branch called Z is created with an apps/ZApp, a new model is created and makemigrations and migrate are executed from that branch. Thus: $ git checkout -b Z $ cd apps $ django-admin startapp Z $ cd .. Then I apply makemigrations and migrate and return to master... When I'm in master, I see those files that should be ignored and I can't find the reason for this ... They shouldn't be there ... All files should be in their respective branch I don't understand ... someone to help me -
The git push heroku master command failed while trying to deploy my django app
i did the git add command the commit command and all then when i wanted to deploy using 'git push heroku master' it failed alot cause i kept retrying it , then i added a Procfile and runtime.txt file to the project directory cause i didnt earlier and it still didnt work. these are the logs from the termina Counting objects: 100% (76/76), done. Delta compression using up to 4 threads Compressing objects: 100% (67/67), done. Writing objects: 100% (76/76), 467.03 KiB | 9.73 MiB/s, done. Total 76 (delta 15), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Installing python-3.9.4 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting absl-py==0.11.0 remote: Downloading absl_py-0.11.0-py3-none-any.whl (127 kB) remote: Collecting alabaster==0.7.12 remote: Downloading alabaster-0.7.12-py2.py3-none-any.whl (14 kB) remote: Collecting altair==4.1.0 remote: Downloading altair-4.1.0-py3-none-any.whl (727 kB) remote: ERROR: Could not find a version that satisfies the requirement anaconda-client==1.7.2 (from -r /tmp/build_39bafa76/requirements.txt (line 4)) (from versions: 1.1.1, 1.2.2) remote: ERROR: No matching distribution found … -
RUNTIME ERROR IN PUT REQUEST DJANGO REST FRAMEWORK
I am trying to upload all user contacts to the server. Meaning if let's say a user registers on the app, the front-end takes all the phone contacts of the user and pushes it to the server so that it can be saved in database of the user. models.py Here in the user model, below you can see I put contact list as a Textfield, and I want to save only the giveName and phoneNumber of the user as a dictionary. class User(AbstractBaseUser,PermissionsMixin): phone = models.CharField(unique=True, max_length=20) username = models.CharField(max_length=50, unique=True) full_name = models.CharField(max_length=40) date_joined = models.DateTimeField(verbose_name='date_joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last_login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_signedup_user = models.BooleanField(default=True) otp = models.CharField(max_length=10, default='') clubs_joined_by_user = models.CharField(max_length=5000, default="") number_of_clubs_joined = models.IntegerField(default=0) contact_list = models.TextField(default='') #this is the contact_list field, where I want user's contact details total_frames_participation = models.IntegerField(default=0) talked_to = models.CharField(max_length=1500,default='') USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['username', 'full_name'] #Since we created a manager for this Custom user model, which we use in the following way below. objects = MyAccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True serializers file ---> I did use a google's (phonenumbers) … -
Django.server logging configuration not working in Django Daphne
I wanted to increase logging level in order to decrease spam in logs with all 2XX responses. According to Django docs and other SO questions I have changed level of django.server logger to WARNING in settings.py. Unfortunately, this change does not work when I run my server using daphne. To verify, I ran my app using manage.py runserver and there the config was working. I've also tried changing log level (using LOGGING = {} in settings.py) of all loggers in logging.root.manager.loggerDict, also unsuccessfully. Anyone has some idea on how to either determine which logger logs the messages like presented below in daphne or how to force daphne to respect django.server log assuming it works as I expect? Sample log message I'm talking about: 127.0.0.1:33724 - - [21/Apr/2021:21:45:13] "GET /api/foo/bar" 200 455 -
How to craete Model Serialziers in django
I have models created and I need to work on Serialziers part. How do i create four tables in database. Table that I need: 1.OrderRoaster: fields = ( 'id', 'importDate', 'countOfOrders', 'importedBy', 'status') 2.OrderDetails: fields = ( 'id', 'detailSrl', 'orderDate', 'salesRep', 'customer', 'product', 'productTotal', 'serviceTotal', 'orderTotal', ) 3.OrderLineItem: fields = ( 'id', 'detailSrl', 'product', 'quantity', 'rate', 'discountPercentage', 'dutyPercentage', 'subTotal' ) models.py class OrderRoaster(models.Model): importDate = models.DateField(default=now) countOfOrders = models.PositiveIntegerField() importedBy = models.ForeignKey(Employee,on_delete=models.CASCADE) status = models.CharField(max_length=20) def __str__(self): return str(self.importedBy) + str(self.importDate) class ProductType(models.Model): productType = models.CharField(max_length=30) def __str__(self): return str(self.productType) class ProductSubType(models.Model): productType = models.ForeignKey(ProductType,on_delete=models.CASCADE) subType = models.CharField(max_length=20) def __str__(self): return str(self.subType) class Product (models.Model): productName = models.CharField(max_length=10) description = models.CharField(max_length=30) productSubType = models.ForeignKey(ProductSubType,on_delete=models.CASCADE) def __str__(self): return str(self.productName) class State(models.Model): stateName = models.CharField(max_length=10) stateCode = models.PositiveSmallIntegerField() def __str__(self): return str(self.stateName) class Address(models.Model): address_line_1 = models.CharField(max_length=30) address_line_2 = models.CharField(max_length=30) state = models.ForeignKey(State, on_delete=models.CASCADE) def __str__(self): return str(self.address_line_1) class OfficeLocation(models.Model): officeName = models.CharField(max_length=10) officeCode = models.CharField(max_length=10) address = models.ForeignKey(Address,on_delete=models.CASCADE) def __str__(self): return str(self.officeName) class CustomerType(models.Model): custType = models.CharField(max_length=20) def __str__(self): return str(self.custType) class Customer(models.Model): custName = models.CharField(max_length=20) address = models.ForeignKey(Address,on_delete=models.CASCADE) custType = models.ForeignKey(CustomerType,on_delete=models.CASCADE) def __str__(self): return str(self.custName) class OrderDetail(models.Model): orderRoaster = models.ForeignKey(OrderRoaster,on_delete=models.CASCADE) detailSrl = models.CharField(max_length=20) orderDate = models.DateField() salesRep = models.ForeignKey(Employee,related_name="salesRep",on_delete=models.CASCADE) admin … -
How to generate Django breadcrumbs automatically
I want to automatically make Django breadcrumbs and I tried too much and was unsuccessful. Is there any help? this is my template : <ul id="bread" class="breadcrumb"> <li class="breadcrumb-item"><a href="{% url 'home' %}">home</a></li> <li class="breadcrumb-item"><a href="{% url 'Categorie' %}">{{category_slug}}</a></li></li> </ul><br/> this is project urls : from django.contrib import admin from django.urls import path , include urlpatterns = [ path('' , include('Product.urls' ) ), path('admin/', admin.site.urls), ] this is my app urls : from django.urls import path from . import views urlpatterns = [ path('' , views.home, name='home' ), path('Product/Categorie_1/' , views.Categorie_1, name='Categorie_1' ), path('Product/Categorie_2/' , views.Categorie_2, name='Categorie_2' ), ] -
Encoding And Decoding File Field into bytes
I have the goal of changing the file object (video uploaded by user) to bytes and then chunking it and then changing these chunks again to images or frames. the following code is a snippet from a django app. def handle_uploaded_file(f): with open('./chunks_made.txt', 'wb+') as destination: for chunk in f.chunks(): print(type(chunk)) print(len(chunk)) destination.write(chunk) chunk_length = len(chunk) read_batches(len(chunk)) def read_batches(chunk_size): with open('./chunks_made.txt', 'rb') as file: content = file.read(chunk_size) frame = cv2.imdecode(content, cv2.IMREAD_COLOR) plt.imshow(frame) plt.show() The process view which calls these functions: def process(request): video_file = request.FILES['video'] handle_uploaded_file(video_file) data = 'some_data' return render(request, 'video/result.html', {'data':video_file}) I don't know how to decode the bytes into the frames as a real image. -
Serializer for invoices without foreignkey detail
I have this models of Order and a nested object OrderDetail. In the OrderDetail and don't want to save the reference to Product. I want to save the product data irself. So, I don't know how to build the serializer class Product(UUIDModel): name = models.CharField(max_length=10) price = models.DecimalField(max_digits=16, decimal_places=2, default=0.0) class Order(UUIDModel): order_name = models.CharField(max_length=10) class OrderDetails(UUIDModel): order = ForeignKey('Order', models.CASCADE, verbose_name=_('order')) product_name = models.CharField(max_length=10) product_price = models.DecimalField(max_digits=16, decimal_places=2, default=0.0) class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order def create(self, validated_data): ... I use Formik to build the forms and I receive products uuid in the serializer. There is a simple way to build this kind of tipical problem ?