Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djoser simpleJWT AUTHORIZATION forbidden(403) whie sending JWT <token> to auth/users/me/
I am using DJOSER and simple jwt for authentication and authorization. when I send a post request for authentication to endpoint http://localhost:8000/auth/jwt/create/ it response with access and refresh token, and again when i pass the Authorization:JWT <access_token> to https://localhost:8000/auth/users/me/ it gives 403 forbidden with "detail": "Authentication credentials were not provided." have my settings like DJOSER = { 'LOGIN_FIELD': 'email', 'SEND_CONFIRMATION_EMAIL': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'PERMISSIONS': { 'activation': ['rest_framework.permissions.AllowAny'], 'password_reset': ['rest_framework.permissions.AllowAny'], 'password_reset_confirm': ['rest_framework.permissions.AllowAny'], 'set_password': ['djoser.permissions.CurrentUserOrAdmin'], 'username_reset': ['rest_framework.permissions.AllowAny'], 'username_reset_confirm': ['rest_framework.permissions.AllowAny'], 'set_username': ['djoser.permissions.CurrentUserOrAdmin'], 'user_create': ['rest_framework.permissions.AllowAny'], 'user_delete': ['djoser.permissions.CurrentUserOrAdmin'], 'user': ['djoser.permissions.CurrentUserOrAdmin'], 'user_list': ['djoser.permissions.CurrentUserOrAdmin'], 'token_create': ['rest_framework.permissions.AllowAny'], 'token_destroy': ['rest_framework.permissions.IsAuthenticated'], }, 'SERIALIZERS': { 'user_create': 'accounts.serializers.UserCreateSerializer', 'user': 'accounts.serializers.UserSerializer' } } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICAITON_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ), } serializers from djoser.serializers import UserCreateSerializer, UserSerializer from django.contrib.auth import get_user_model from rest_framework import serializers User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ('id', 'email', 'first_name', 'last_name', 'password') user model from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None, is_staff=False, is_admin=False, is_active=True): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have password") if not first_name: raise … -
Custom encoder ignored by django JsonResponse
I am building an app using Django Rest Framework (Versions : django 3.1, djangorestframework 3.11.1, python 3.7) I want to override the encoder used in JsonResponse. An oversimplification of my problem: from django.http import JsonResponse from django.core.serializers.json import DjangoJSONEncoder class CustomEncoder(DjangoJSONEncoder): def default(self, o): return o + 10 response = JsonResponse({"data": 1}, encoder=CustomEncoder) What I expect from response.getvalue() is '{"data": 11}' but instead I get '{"data": 1}'. What am I doing wrong ? -
How to set default inner serializer data in django-rest?
I have two simple serializers class UserSerializer(Serializer); name = serializers.CharField(required=False, default='Mile') age = serializers.IntegerField(required=False, default=25) class AccountSerializer(Serializer): account_id = serializers.UUIDField(required=False, default=uuid4()) user = UserSerializer() And i want to set the default user in AccountSerializer if it is not specified. For example, account = AccountSerializer(data={'account_id': uuid.UUID('e623429d-b1d1-4238-91b8-03e6f5ec58f1')}) account.is_valid() account.data { 'account_id': 'e623429d-b1d1-4238-91b8-03e6f5ec58f1', 'user': { 'name': 'Mike', # user must be default 'age': 25 } } And i also want to set my own values in 'user fields' and leave the other fields by default For example, account = AccountSerializer(data={'account_id': uuid.UUID('e623429d-b1d1-4238-91b8-03e6f5ec58f1'), 'user': {'name': 'Julie'}}) account.is_valid() account.data { 'account_id': 'e623429d-b1d1-4238-91b8-03e6f5ec58f1', 'user': { 'name': 'Julie', # user name must be 'Julie' but age by default 'age': 25 } } How should i implement this? Please note that I am not going to save the model to the database! I just need to check the incoming json and set the fields to default if not set -
cannot generate token s for other users, only able to generate token for admin in Django rest framework
Im new to Django Rest framework and working with token authentication but the problem is Im only able to generate token for admin/superuser not for other users on save. I would like to generate tokens for other users on register but cant figure out how to do it. I am getting this error ValueError: Cannot query "k@hotmail.coml": Must be "User" instance. I would really appreciate if someone could help me resolve it. models. py file. from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token # Create your models here. class Task(models.Model): title= models.CharField(max_length=200) complete= models.BooleanField(default=False) created= models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) 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 = … -
Can a Docker remote host keep its files synced with your local machine? Django project that needs auto-reloading
I'm considering the purchase of one of the new Macbook M1's. Docker Desktop is apparently unworkable with their Rosetta 2 engine, and all of my development efforts rely on Docker desktop, and a local development environment that auto-reloads when files are changed. I haven't done much with Docker remote hosts, but I see that this could be a stop-gap solution until Docker rewrites its engine. Google is failing me... can you keep files on your local machine synced up with your Docker remote host? -
URL is changing after my image is update in django
When I add an image, the URL of the image is fully visible but when I update, it is half past this is my models.py from django.db import models # Create your models here. class ImageUpload(models.Model): get_image = models.FileField(upload_to='gallery/new/',null=True) this is my views.py from django.shortcuts import render,redirect from upload.models import ImageUpload # Create your views here. def add_image(request): if request.method == "POST": image = request.FILES['myimage'] save_image = ImageUpload(get_image=image) save_image.save() return redirect('/') else: image_data = ImageUpload.objects.all() return render(request,'add_image.html',{'image_data':image_data}) def update_image(request, id): if request.method == "POST": image = request.FILES['myimage'] save_image = ImageUpload.objects.filter(id=id).update(get_image=image) return redirect('/') else: image_data = ImageUpload.objects.filter(id=id) return render(request,'update_image.html',{'image_data':image_data}) this is my urls.py from django.urls import path from upload.views import add_image, update_image app_name = 'upload' urlpatterns = [ path('', add_image, name="add_image"), path('update_image/<id>/', update_image, name="update_image"), ] this is my settings.py static and media configuration STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = BASE_DIR.parent / "static_cdn" MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / "media" this is my project urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('upload.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is my add_image.html <form action="{% … -
Getting irrevelant errors in my background task functions
I have a Django application and I'm using django-background-tasks library in it. When I run my background functions, I'm getting irrelevant errors. I'm getting an error such as below even if I send the arguments to that function. Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/background_task/tasks.py", line 43, in bg_runner func(*args, **kwargs) TypeError: optimize_task() missing 2 required positional arguments: 'optimization_outputs' and 'model_names Here is the function calling; optimize_task(customer_name, request.user.id, known_map, bounds, optimization_features, optimization_outputs, model_names, verbose_name = verbose) I'm getting not just this error, but irrelevant errors like this and that. How can I fix this issue? -
How To Post List String for Django Rest Framework
class ArticleTagViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleTags fields = ('id','tag') def create(self, validated_data): return ArticleTags.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): tags_set = ArticleTagViewSerializer(source='posttags',required=False,many=True) class Meta: model = Article fields = ('id','caption','tags_set') def create(self, validated_data): return Article.objects.create(**validated_data) Hey guys,what i want to do is save List 's one by one when they are sent as post request like this { "caption": "Caption", "tags_set": [ { "id": "9d7b305d-939b-48ea-bea0-2e386f4bd8ff", "tag": "Tag1" }, { "id": "18f76a4c-f29d-4c99-ae0d-d03d1b00d070", "tag": "Tag2" } ], } I know that i have to create such a create() function like this: def create(self, validated_data): tags = ???? articleinit = Article.objects.create(**validated_data) for tagtinit in list(tags): m2 = ArticleTags(article=articleinit , tag= taginit ) m2.save() return articleinit but how do i request the tags such that create function works as intended? -
How to edit empty field directly on list in django admin
I have a problem with editing empty fields directly in the list in the django admin panel, it's about the name field. I set list_editable to name, but now it is possible to edit all fields, not empty ones. Do I need to overwrite something? models.py class Person(models.Model): name = models.CharField(max_length=255, blank=True) numer = models.IntegerField() text = models.TextField() def __str__(self): return str(self.numer) admin.py @admin.register(Person) class PersonAdmin(admin.ModelAdmin): ordering = ['numer'] list_display = ['numer', 'name'] list_editable = ['name'] -
'str' object has no attribute 'makefile' I had this error when i run the page?
I had this problem and I dont know whats the meaning of makefile is ?!! thanks for ur help this url page code : from django.contrib import admin from django.urls import path from tiketing.views import movie_list urlpatterns = [ path('admin/', admin.site.urls), path('tiketing/movie/list/', movie_list) ] and this is my view page code def movie_list(request): movies = Movie.objects.all() response_text = '\n'.join('{}:{}'.format(i, movie) for i, movie in enumerate(movies, start=1) ) return HTTPResponse(response_text) -
how to call a template passing a new parameter, but the template should have parameters that was passed to it when it was called by different view
1: i have a template shop.html. view.py ---> i have passed multiple parameters to the page like def shop(request): context {'parameter1 parameter2 parameter3 parameter4 parameter5 '} return render(request, 'shop.html', context) 2: now i am calling the same template, but this time with different view i want to pass another parameter i.e parameter6 but this time. i dont want to write the queries again to pass parameter1 to 5 that i passed in def shop(); 3: how can i pass additional parameter to the template using another view view.py ---> def add_value(request): query = xxxxxxxxxxxxxxx return render(request, 'shop.html', {query:query}) 4: when i would go to shop.html again. i should get all the parameters passed to shop.html by def shop() and def add_value() plz help. thanks you -
AttributeError: object has no attribute "object_list"
I'm trying to bring an old django app up to date but hitting an error I am unable to figure out. After upgrading django from 1.5 to 1.8, I'm suddenly getting the error AttributeError: MonthlyStatementPdf has no attribute object_list. The code in question is class MonthlyStatementPdf(BaseTableView): table_class = MonthlyStatementTable template_name = 'reports/monthly_statement_pdf.html' permission_required = 'core.view_reports' def get_context_data(self, **kwargs): context = super(MonthlyStatementPdf, self).get_context_data(**kwargs) context['summary'] = self.request.session.get('monthly_statement', {}).get('summary', 0) context['merchant'] = self.request.session.get('monthly_statement', {}).get('merchant') context['period'] = self.request.session.get('monthly_statement', {}).get('period', timezone.now()) if context['merchant']: context['discount_rate'] = context['merchant'].discount_rate / 100 return context def get_queryset(self): return self.request.session.get('monthly_statement', {}).get('daily_totals', []) def get(self, request, *args, **kwargs): context = self.get_context_data(object_list=self.get_queryset()) pdf_file = generate_pdf(request, context, self.template_name) response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="MonthlyStatement.pdf"' return response I have no prior experience with django, or python for that matter, but obviously it is an error with how object_list is being passed to get_context_data in the get method. I tried referencing the answer to this similar question, which seems to make sense. If I understand correctly, this code is trying to pass object_list from get to get_context_data, which proceeds to call the super method, but object_list is actually set from inside the get method somewhere up the chain of inheritance (django generic list view, it … -
DRF: problem with permissions of no staff members
I'm having problems with the permissions with Django Rest Frameworks. I have 2 settings file, one for dev and the other for production. In the production file I have this permission class 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) It works when you use the token authentication but this is the problem: If I go in as a normal user (not even a staff member) I receive this when I try to go to http://myapp/drf/ (this is the link of my django rest framework) I receive this error: AttributeError at /drf/ 'TokenAuthentication' object has no attribute 'has_permission' Not even sure if that's fine but the true problem comes when I try to access some of the elements, for example: http://myapp/drf/clients Then any user can see all the clients with no restriction. It is like these restrictions only works for the root of django rest framework. What can I do? -
Carousel item position changes everyday!! (Django , materialize)
My Carousel/Carousel-Item dimensions are not fitting in nicely on the page. I left it at 1800px yesterday and there was no gap between navbar and carousel item. now there is. (gap) Not sure where i'm going wrong. When i reduce the carousel size to 900 px it cuts off lines from the carousel item as described below. carousel item over extending past carousel's height, hence misses lines Here's the html code in my django template. {% load staticfiles %} {% load static %} {% load index %} <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="{% static 'style.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <nav> <div class="container nav-wrapper"> <div class="flex-container"> <h class="brand-logo center"><b>Today's Q/A</b></h> <ul id="nav-mobile" class="Center"> <li><a href="/"></a></li> </ul> </div> </div> </nav> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script> $(document).ready(function(){ $('.carousel').carousel(); }); autoplay() function autoplay() { $('.carousel').carousel('next'); setTimeout(autoplay, 4500); } </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> {#<section class="black">#} <style> html, body{ background-color: #FEDCC8; } .flex-container { display: flex; flex-direction: row; flex-wrap: wrap; justify-content: space-evenly; } </style> <div class="flex-container"> <div class="container-fluid"> <a class="btn waves-effect waves-light" href="/random_naturemetal_link">Cute Cat Pic <3 <i class="large material-icons left">sentiment_neutral</i> <i class="large material-icons right">sentiment_very_satisfied</i> </a> </div> <div class="container-fluid"> <a class="btn waves-effect waves-light" href="/random_cozy_link"> C O Z Y … -
Why can't I use the same variable again in Django? [duplicate]
In my views.py I have a function dataPrint(), which returns page, and dictionary categories_zipped. But when I try to use this dictionary in my skills.html file using Django syntax {% for category in categories_zipped %} it works only for the first time, when I try to use it later, it does not work. (I'm not getting any errors, the second use, just returns nothing, as shown on the images below) def dataPrint(request): categories = [ 'all', 'javascript', 'html', ] categories_menu = [ 'All', 'JS', 'HTML', ] return render(request, 'skill/skills.html', {'categories_zipped': zip(categories, categories_menu}) skills.html {% for category in categories_zipped %} <a class="link-icon" href="/skills/{{category.0}}"> <img class="small-icon" src="{% static '/skillsgraph/img/' %}{{category.0}}.svg" alt="{{category.0}}'.svg'" /> <span class="icon-title">{{category.1}}</span> </a> {% endfor %} <select name="category" class="link-list"> {% for cat in categories_zipped %} <option value="{{ cat.0 }}">{{ cat.1 }}</option> {% endfor %} </select> It renders only for the first time and renders only the first thing. If I change order (put select before a), it works only for select, but not for a's. -
How to inherit a model object instead of the model class
For some reasons, I want my Boolean Fields in my class Items(models.Model) to have a foreign key in my class ItemsGotten(models.Model). Here's my code for better understanding... Items(models.Model): title=models.Charfield(max_length=180) description=models.Textfield(max_length=180) paper=models.BooleanField(default=False, blank=True) skin=models.BooleanField(default=False, blank=True) ItemsGotten(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) paperitem = models.ForeignKey(???) skinitem = models.ForeignKey(???)``` I know that you can simply get the value of the whole model class e.g paperitem = models.ForeignKey(Items). But that's not what I want to achieve, I want to get only the object from the Items model. e.g skinitem = models.ForeignKey(Items.skin). Thanks -
How to capture values in checked checkboxes using Django
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is having a views.py function to take the information of which products were selected and subtracting 1 from the quantity of the database. When I say print(products) in my views.py, it returns "[]" in my terminal. This means that the values in my checked checkboxes are not being captured. Can anyone help me solve this? """models.py""" class Post(models.Model): title = models.CharField(max_length=100) Price = models.DecimalField(max_digits=4, decimal_places=2,default=1) Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1) quantity = models.IntegerField(default=1) author = models.ForeignKey(User, on_delete=models.CASCADE) category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def inventory(request): products = request.POST.getlist('products') a = Post.objects.filter(title=products).update( quantity=F('quantity')-1 ) return redirect('blog-home') urls.py path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('inventory', views.inventory, name='inventory'), home.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} {% if post.quantity > 0 %} <input type="checkbox" … -
Django pdfkit.from_string gives wkhtmltopdf OS error for large html string while converting to pdf
I am facing this issue and searched a lot for this, but found no solution. I am using pdfkit in my django application to generate invoices. I create a template in django and then render it with my data in an html string and then pass that rendered html string to pdfkit. When I generate 100 - 110 pages it prints pdf successfully. More than these pages, like 140 or 150 it gives an OS error content loaded unsuccessfully. from django.template.loader import get_template import pdfkit class CourierInvoice(View): def get(self, request, *args, **kwargs): options = { 'page-size': 'A4', 'dpi': 400, 'disable-smart-shrinking': '' } context = { ... //Data goes here for html ... } template = get_template("bulk_courier_invoices.html") html = template.render(context) # Renders the template with the context data. try: pdf = pdfkit.from_string(html, False, options) except: return HttpResponse("Some Error Occurred Try printing with less pages") response = HttpResponse(pdf, content_type='application/pdf') filename = "CourierInvoices_" + datetime.today().strftime('%d-%m-%Y') + ".pdf" content = "attachment; filename=" + filename response['Content-Disposition'] = content return response -
Get anchor tag from Django request URL
I have a Django template filter where I'm trying to check the request URL to see whether it includes an anchor tag or not. For example, I want to check if the request URL is: /mypath/mypage/my-slug/ or /mypath/mypage/my-slug/#myanchor If it is the latter, I want to get the anchor tag ID. Currently, the anchor tag seems to be stripped from the request information: request.path, request.build_absolute_uri() and so on. I can only get /mypath/mypage/my-slug/. The URL pattern for the page in question is: re_path(r'^(?P<product_slug>[\w-]*)_(?P<pk>\d+)/$', self.detail_view.as_view(), name='detail') I can see the regex looks for the line end after the last slash, which suggests the anchor is being excluded, but I can easily retrieve GET params from the URL and I expected this to be straightforward too. It feels like I am missing something pretty obvious. -
Is there a way to use Firestore with Pyrebase Django
Hey I would like to use Firestore as db in my app rather than RTDB. Is there any way to use firestore with Pyrebase? More over ,if this is not possible, I already tried to use firebase_admin in order to use firestore, But I encountered a problem with authenticating users. When I looked into firebase documentation I saw that there is no native way to authenticate user via Python. https://firebase.google.com/docs/auth, I did find a JS script that can do the job,Is it good practice? is There any security issue with this? ``firebase.auth().createUserWithEmailAndPassword(email, password) .then((user) => { // Signed in // ... }) .catch((error) => { var errorCode = error.code; var errorMessage = error.message; // .. }); `` Any solutions? -
Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['post_share/(?P<post_id>[0-9]+)$']
views.py def post_share(request, post_id): post = get_object_or_404(Post,id=post_id) sent = False if request.method == 'POST': form = EmailPost(request.POST) if form.is_valid(): cd = form.cleaned_data post_url = request.build_absolute_url(post.get_absolute_url()) subject = f"{cd['name_subject']} recommends you read " \ f"{post.post_title}" message = f"Read {post.post_title} at {post_url}/n/n" \ f"{cd['name_subject']}\'s description: {cd['description']}" send_mail(subject,message, '--------@gmail.com', [cd['send_to']]) sent = True else: form = EmailPost() return render(request, 'mains/post_share.html', {'post':post,'form':form,'sent':sent}) urls.py path('post_share/<int:post_id>',views.post_share,name='post_share'), forms.py class EmailPost(forms.Form): name_subject = forms.CharField(max_length=400) email = forms.EmailField() send_to = forms.EmailField() description = forms.CharField(required=False,widget=forms.Textarea) show_more.html <p><a href="{% url 'mains:post_share' post.id %}">Share this post</a></p> When i click on Share this post ( link ) in share_more.html Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['post_share/(?P<post_id>[0-9]+)$']. I have tried everything but nothing happens. Please have a look and Please help me in this. I will really appreciate your Help. -
Git submodule: git@github.com: Permission denied (publickey). fatal: Could not read from remote repository
I have a problem with git submodule update --init --remote. I receive errors: Permission denied and Failed to clone. But I added SSH keys to my github repository. I can pull, push, git clone. I have all needed accesses. I use OS Windows 10. I changed in .gitmodules file url=git@github.com:xxx to url=https://github.com/xxx , but not helped. -
How can i access an attribute from another table through many to many relationship in Django?
I am a beginner in django this might be a silly question. I want to access the product table's selling_price & other's data through the order table. This my view.py def createOrder(request): form = OrderForm() if request.method == 'POST': # print('Printing POST:',request.POST) form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('order') context={'form':form} return render(request,'accounts/order_form.html',context) This is my model.py class Order(models.Model): STATUS=( ('paid','paid'), ('due','due'), ('cancel','cancel') ) customer=models.ForeignKey(Customer,null=True,on_delete=models.SET_NULL) product=models.ManyToManyField(Product) discount=models.FloatField(max_length=200,null=True) total=models.FloatField(max_length=200,null=True) paid=models.FloatField(max_length=200,null=True) due=models.FloatField(max_length=200,null=True) status=models.CharField(max_length=200,choices=STATUS) create_date=models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.product.name Here you can see in model i have a many to many relationship with product. Can i get product table's other's details on template through this relationship. <div class="form-group col-md-4"> <label for="name">Product</label> <!-- {{form.product|add_class:"form-control select2bs4"}} --> {% render_field form.product|add_class:"form-control select2bs4" id='productdropdown' %} </div> For say i want to get the selling_price,purchase price of product table instead of a name in the dropdown how can i do that. -
Use checksum to verify integrity of uploaded and downloaded files from AWS S3 via Django
Using Django I am trying to upload multiple files in AWS S3. The file size may vary from 500 MB to 2 GB. I need to check the integrity of both uploaded and downloaded files. I have seen that using PUT operation I can upload a single object up to 5GB in size. They also provide 'ContentMD5' option to verify the file. My questions are: Should I use PUT option if I upload a file larger than 1 GB? Because generating MD5 checksum of such file may exceed system memory. How can I solve this issue? Or is there any better solution available for this task? To download the file with checksum, AWS has get_object()function. My questions are: Is it okay to use this function to downlaod multiple files? How can I use it to download multiple files with checksum from S3? I look for some example but there is noting much. Now I am using following code to download and serve multiple files as a zip in Django. I want to serve the files as zip with checksum to validate the transfer. s3 = boto3.resource('s3', aws_access_key_id=base.AWS_ACCESS_KEY_ID, aws_secret_access_key=base.AWS_SECRET_ACCESS_KEY) bucket = s3.Bucket(base.AWS_STORAGE_BUCKET_NAME) s3_file_path = bucket.objects.filter(Prefix='media/{}/'.format(url.split('/')[-1])) # set up zip folder zip_subdir … -
How can I integrate Tailwind css into my Django project with Docker?
I'm trying to use Tailwind CSS in my Django project running with Docker / Docker-compose. my Django container is built with python:3.9-slim, which has no npm built-in. I am thinking to use node:15.4-alpine to install tailwind css. How can I do so? Can someone give me guidance on Dockerfile and docker-compose.yml I've tried to start with this tailwind playground. But I don't need to run the live-server.