Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cashing all the static assets at once in a service worker in PWA
My question is about caching all the static assets present in a seperate directory (for me it is 'static') at once in the service worker in a PWA. As we know we need to provide a path to the asset to be cashed. E.g, if we want to cache an image 'img.png' then we need to do something like this; cache.add(/static/img.png) where cache is the element returned by caches.open(). And if we want to add multiple files we can do something like this; assets = [ 'static/img1.png', 'static/img2.png' ] // and so on. cache.addAll(assets); What i want to know is that if there is any way to pass directly all the files present in static folder like; cache.add(/static); But the above line is not working as we can only pass a valid path(URL) not a folder or just a file. -
I want to only fetch a specific field data
Hello in my order model i have these fields : class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey( Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True, blank=True) From here i have total field where i want to create a result depend on quantity and price.For an example price * quantity = total After that i want to fetch only the total I am new in django really confused about this Please help -
"Permission Denied" when accessing private keys downloaded from S3 to elastic beanstalk
I stored Firebase Admin SDK credential into elastic beanstalk env from amazon S3 on app's deployment according to the official AWS doc. https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/https-storingprivatekeys.html When Firebase Admin SDK tries to access the key it raises error. PermissionError: [Errno 13] Permission denied: '/etc/pki/tls/certs/my_cert.json' How can I setup make it work? -
docker - How to set up environment database for docker-compose.yml file from env.ini file outide?
This is my docker-compose.yml which I hard-code the information of database, I want to input in it from a file env.ini of mine before pushing it to GitLab for safety but dont know how to do it. version: "3.8" services: db: image: postgres environment: - POSTGRES_DB=####### Hide these information and take it from - POSTGRES_USER=##### another file when running it - POSTGRES_HOST=172##### - POSTGRES_PASSWORD=######### web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Plus: my file env.ini is quite complicated since its contains a lot of others information, it looks like this: [sv_info] host = ######### user = ######## password = ######## database = # venus_base_url = ################# venus_auth_key = cargo_base_url = ################# cargo_awb_acckey = ################# cargo_awb_cusnum = ################# cargo_awb_user = ################# cargo_awb_revkey = ################# [heremap_info] url = ################# api_key = ################# Usually, I use from configparser import ConfigParser in Python to work with this env.ini in my code. -
Django file upload shows None: HTTP 400 Bad Request
I am receiving multipart/form-data in my django api.My task is to send same data to other server(api). class CreativeUploadViewset(viewsets.ViewSet): def create(self,request, format=None): file_path = request.query_params.get('file_path', None) file_type = request.query_params.get('file_type', None) member_id = request.query_params.get('member_id', None) in_memory_uploaded_file = request.FILES['file'].file.getvalue() files = {'file': in_memory_uploaded_file, 'type': ('image')} response_data = CREATIVE_UPLOAD.create(data = None, files=files,headers={"Content-Type": "multipart/form-data", "boundary":request.headers["Content-Type"][30:]}) return Response(response_data) CREATIVE_UPLOAD.create() hits the other server api. When i hit the other server i get following error: **"None: HTTP 400 Bad Request"** When i googled i got to know we should include 'boundary' parameter in headers. Things to note I tried this in both python 3.6 and later versions. in_memory_uploaded_file looks somethind like this: b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x06\x1d\x00\x00\x01\xe2\x08\x06\x00\x00\x00\xfc\x95\r4\x00\x00\x00\x04sBIT\ ......... It works if i directly sent image or video file from postman to the other server. -
Using Validators to validate Words in Comments not working
I am trying to validate Comments in Posts to ensure that there are no bad words used in it. I have checked about Writing validators but it is not working and I am not sure what is the reason. The badwords.txt location is: C:\Users\User\Desktop\Project\badwords.txt The function lives in the models.py: with open("badwords.txt") as f: CENSORED_WORDS = f.readlines() def validate_comment_text(text): words = set(re.sub("[^\w]", " ", text).split()) if any(censored_word in words for censored_word in CENSORED_WORDS): raise ValidationError(f"{censored_word} is censored!") class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300, validators=[validate_comment_text,]) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) My question: What am I doing wrong and how do I get this function to work? -
Same api endpoint for CRUD operations in Django generic apiview
I have been creating different api endpoint for different requests, for eg every single api for get, post, delete and update in generic apiview. But my frontend developer has told me it's a very bad practice and I need to have a single api for all those 4 requests. When I looked it up in the documentation, there is a ListCreateApiView for listing and creating an object, but I cant use it for delete and also for update. How can I include those two in a single endpoint. I don't use modelset view and also functional view. I mostly use generic api views. -
How to correctly use Django reverse FK lookup to show instances of the child model in CBV
I have two models, field of one of them pointing to the other as shown below: class Group(models.Model): group_company_id = models.CharField(primary_key=True, ...) class Company(models.Model): company_id = models.CharField(primary_key=True, ...) group_company = models.ForeignKey(Group, related_name="related_grp_company", ...) I am trying to get all the Companies that have been created for a particular Group. So I am trying to get the company_id (and other) values in Djnago UpdateView as a list in the template. My CBV is as shown: class GroupCompanyChangeView(UpdateView): template_name = ... model = Group form_class = ... success_url = reverse_lazy('group_list') grp_coy_units = GroupCompany.objects.prefetch_related('related_grp_company') # I am trying to get the values of `company_id` in the template but nothing is displayed. Could somebody please let me know how to get this to work? -
Adding get_context_data method to a class based view breaks django-tables2
I have a class-based view that I use to obtain a queryset and pass to django-tables2 which renders the result. That aspect all works fine. I am trying to pass a record instance from a different queryset to the template, so I can display information above the table django-tables2 produces. Upon searching, it seems the 'right' way to do so is via the get_context_data method. However when I attempt do add this method to my view, simply obtaining the queryset and returning it, it produces an error Expected table or queryset, not str. I isolated this to being due to {% render_table table %} in my template. Without that, I can access my 'team' object as intended. Why is this happening? The qs queryset was being passed fine to django-tables2 before I added my get_context_data method. Does the qs queryset have to be returned via get_context_data as well? If so, why? This is my attempt: class myteam(LoginRequiredMixin, SingleTableView): def get_queryset(self): qs = Contestant.objects.filter(assigned_team=self.request.user.contestant.assigned_team) qs = qs.exclude(id=self.request.user.contestant.id) return qs def get_template_names(self): return 'xgames/viewteam.html' def get_table_class(self): return TeamsTable def get_context_data(self): team = Team.objects.get(id=self.request.user.contestant.assigned_team.id) return {"team": team} -
i created a django software its running on localhost,but not working on heroku its log is showing this
ink to github for that software is https://github.com/ShubhamSjain2000/stockware.git 2020-11-28T07:50:10.254987+00:00 app[api]: Release v4 created by user shubham1900jain@gmail.com 2020-11-28T07:50:10.531132+00:00 app[api]: Deploy d9583d0a by user shubham1900jain@gmail.com 2020-11-28T07:50:10.531132+00:00 app[api]: Release v5 created by user shubham1900jain@gmail.com 2020-11-28T07:50:20.000000+00:00 app[api]: Build succeeded 2020-11-28T07:50:35.159601+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=stockware.herokuapp.com request_id=0b1c2b67-1ac9-4247-8f90-fb928da59cd6 fwd="182.70.189.243" dyno= connect= service= status=503 bytes= protocol=https 2020-11-28T07:50:36.170169+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=stockware.herokuapp.com request_id=af302f4c-e5cc-405e-ba97-30a07516c784 fwd="182.70.189.243" dyno= connect= service= status=503 bytes= protocol=https 2020-11-29T04:12:18.801989+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=stockware.herokuapp.com request_id=e9644275-2548-4405-8dab-7f58291c79ec fwd="182.70.190.109" dyno= connect= service= status=503 bytes= protocol=https 2020-11-29T04:12:23.337106+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=stockware.herokuapp.com request_id=54638bf1-67b2-4982-8e2c-365826a046f2 fwd="182.70.190.109" dyno= connect= service= status=503 bytes= protocol=https 2020-11-29T04:19:50.571393+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=stockware.herokuapp.com request_id=ac335c25-ed5e-4faa-909d-9208375721f7 fwd="182.70.190.109" dyno= connect= service= status=503 bytes= protocol=https 2020-11-29T04:19:51.945843+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=stockware.herokuapp.com request_id=ba9f09fb-8aff-4096-af16-cb673534520e fwd="182.70.190.109" dyno= connect= service= status=503 bytes= protocol=https -
djoser reset password keeps returning 403 forbidden
I have djoser running with rest framework and simpleJWT for authentication and I have a react frontend, everything is working fine except when the frontend sends the post request to "..../auth/users/reset_password", it gives back a 403 forbidden and it does not send an email with the link containing the uid and token, I cannot seem to find the problem, can someone help with this issue?? here is the settings: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', 'rest_framework.permissions.IsAuthenticated', ] } DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'LOGOUT_ON_PASSWORD_CHANGE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'authentication.api.serializers.UserCreateSerializer', 'user': 'authentication.api.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'AUTH_HEADER_TYPES': ('JWT',), } -
Calling djangorestframework API functions from a chrome extension (django)
I'm able to log in from the chrome extension with django-rest-auth: https://django-rest-auth.readthedocs.io/ I was told in #django on freenode that I need to use the sessionid it gives me as a cookie when I make requests to the API. At the moment, after I log in (which works), whenever I try to make requests to the API, I get 401 Unauthorized errors. Anyone know why? My jquery code (irrelevant code has been omitted): API = { create_tutorial : function(){ $.ajax({ url: API.url_base + '/api/create_tutorial/', type: 'POST', datatype:'json', data: { title: $('#title').val(), }, xhrFields : { withCredentials: true, }, success: function(d) { Data.current_working_tut = d.id; Template.resets.reset_tut_create_form(); $('#create-tut-2-tab').click(); }, }); }, } My DRF code (irrelevant code has been omitted) @api_view(['POST']) @permission_classes((IsAuthenticated,)) @ensure_csrf_cookie def create_tutorial(request): if request.method == 'POST' and request.is_ajax(): data = request.POST tutorial = Tutorial.objects.create( title=data.get('title'), page_url=data.get('page_url') ) return Response({'msg': 'successfully created tutorial', 'id': tutorial.id}) Please help. Thanks in advance -
'bool' object is not iterable when trying to exclude a row from a filtered queryset with django
I have two models, contestant and team, setup like so: class Contestant(models.Model): contestant_email = models.EmailField(max_length = 254) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) assigned_team = models.ForeignKey('Team', on_delete=models.SET_NULL, blank=True, null=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) class Team(models.Model): team_name = models.CharField(max_length=200) team_description = models.CharField(max_length=200) team_leader = models.ForeignKey(Contestant, on_delete=models.SET_NULL, blank=True, null=True) In a queryset, I am filtering contestants to be limited to the same team as the requesting user. I am then trying to exclude the current user from being included in the the results. My attempt is: class myteam(LoginRequiredMixin, SingleTableView): def get_queryset(self): qs = Contestant.objects.filter(assigned_team=self.request.user.contestant.assigned_team) qs = qs.exclude(id==self.request.user.contestant.id) return qs def get_template_names(self): return 'xgames/viewteam.html' def get_table_class(self): return TeamTable This gives the error 'bool' object is not iterable Why is this? What is the issue in excluding one record from a filtered set? -
I am getting empty values when i print a variable
Actually i am trying to build a virtual payment system. Its simple and easy but ITs not working. I have a veiw for UserInvoice for this payment method : class UserInvoice(View): def map_func(self, product): cart = self.request.session.get('cart', None) product_id = str(product.id) if product_id in cart: return product.price * cart[product_id] def get(self, request, id): user_orders = Order.objects.get(pk=id) args = {'user_orders':user_orders} return render(self.request, 'Home/invoice.html', args) def post(self, request, *args, **kwargs): ids = list(request.session.get('cart').keys()) cart_products = Product.get_products_id(ids) product_prices = list(map(self.map_func, cart_products)) print(product_prices) total_due = sum(product_prices) print(total_due) balance = request.session['customer']['coin'] if balance >= total_due: balance = balance - total_due print(balance) # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer = Customer.objects.get(id = request.session['customer']['id']) customer.coin = balance customer.save() request.session['customer']['coin'] = balance return HttpResponse("Remaining balance: " + str(balance)) return HttpResponse("Failed") Here i tried to fetch cat total and customer balance. After that i want to substract total balance with Cart total. When i try to print total_due it returns me 0, and also when i try to print products prices i mean cart total it also return empty queryset.Fot that reason this method is not working properly. But i have same function to find out the cart total in cart page Here it is : class Cart(View): ## Changes def … -
Accessing Objects Attributes Within Ajax
I am adding ajax to my website. I originally had this button: {% for item in notifications %} <a class='delete' href="{% url 'delete' item.slug %}"> But changed it to Ajax. {% for item in notifications %} <a class='delete'> $(document).on('click', '.delete', function (e) { $.ajax({ url: '/users/ajax/delete/', data: { // here I was to call the 'delete' function in the 'django.notifications' package // something like 'notifications.delete(slug)' }, dataType: 'json', success: function (data) { alert("Working"); } }); }); This Ajax fires correctly, but I don't know how to get item.slug in Ajax. I guess I could do this <a class='delete' slug="{{ item.slug }}"> and access the slug, but it seems really sloppy. Is there a way to pass an object's attributes to Ajax without setting it as a value within the html code itself? Thank you. -
Server Error 500 for serving Media files on Heroku Django?
Everything is working locally with DEBUG = True, but not False. Adding the media urls to the urlpatterns fixed everything locally for DEBUG = False. But I'm still getting Server Error 500 on Heroku when trying to display these images which are located in MEDIA... Any ideas how to fix? Here is the error from heroku with DEBUG = True: -
VS Code Python extension prompts me to select an interpreter when one is selected
I am trying to debug my Django application, but VS Code's Python extension prompts me to select an interpreter any time I hit run, even after I've selected the Python executable in my virtual environment. launch.json { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": ["runserver", "localhost:9000", "--noreload"], "django": true, "console": "externalTerminal" } ] } What can I do to make this pesky alert go away so I can start debugging? -
How do I reference my own record in a model in a Django view?
I have two models, Contestant and Team, which have a relationship with each other. They are defined like so: class Contestant(models.Model): contestant_email = models.EmailField(max_length = 254) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) assigned_team = models.ForeignKey('Team', on_delete=models.SET_NULL, blank=True, null=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) class Team(models.Model): team_name = models.CharField(max_length=200) team_description = models.CharField(max_length=200) team_leader = models.ForeignKey(Contestant, on_delete=models.SET_NULL, blank=True, null=True) I'm trying to build a link "My Team", which will show all the contestants on the team of the logged in contestant. I can't hardcode this, so need to get the contestants team in the view somehow so I can filter my queryset. I got as far as this attempt below: class myteam(LoginRequiredMixin, SingleTableView): def get_queryset(self): qs = Contestant.objects.filter(assigned_team__id=self.request.user__assigned_team__id) return qs def get_template_names(self): return 'xgames/viewteam.html' def get_table_class(self): return TeamTable I realize my attempt of assigned_team__id=self.request.user__assigned_team__id is incorrect, but I also realized I can't see any way to retrieve the team id of the user calling the view and use it to filter my queryset. This has to be a pretty common use case and I'm sure there is a simple solution, but I haven't been able to figure it out, and searching brings up too many unrelated results. What is the correct … -
Django collected static files are not accessible by templates
I've created a django project with some apps. Initially, I just had a single app and i had static files and templates in it. As my project grew, I added some other apps to the project which they are still accessing the statics files and templates from inside the main app. I wasn't giving much care to this problem until i tried to make a simple production and used collectstatic command. Seems i can collect my static files to the STATIC_ROOT directory but i can't access them in the templates. Here is my project structure: shop/ -myshop(main app) --statics --templates -(some other apps beside main app) -shop(directory created by project containing settings.py, manage.py) This is my relevant settings.py configurations: BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ... ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'myshop/static', ] STATIC_ROOT = BASE_DIR / 'static' After running collectstatic django creates the static directory in root of project but when i remove or rename the myshop/static i get static files 404 in runserver. I dont know how to check {% load static %} resulting path in runtime to put more information here. What's wrong? -
Retrieving current user id inside a function defined into class (CreateView)
Is possible to retrieve the current logged user id into a function defined inside a class, in views.py, using Django CreateView? Something like this: class CreationClass(CreateView): model = Mymodel def creation(self, request): form = myForm() user_id = self.request.user.id -
NoReverseMatch at /products/ Reverse for 'product-update' with arguments '('',)' not found. 1 pattern(s) tried: ['products/(?P<pk>[0-9]+)/edit/$']
Struggling with some code. I have seen a lot of people have had this problem, but I can't seem to get their code fixes to work with mine (of course modifying to fit my project). I am still really new to this. I want to be able to edit a product from the list of products on product_list.html. I have created a HTML page called product_update.html in which you can edit the product, and this works. But I would like to direct an 'Edit' link on the product_list page to that product_update page. I am getting this error: NoReverseMatch at /products/ Reverse for 'product-update' with arguments '('',)' not found. 1 pattern(s) tried: ['products/(?P[0-9]+)/edit/$'] Here is my code: views.py from django.http import Http404 from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import UpdateView from .forms import ProductForm, RawProductForm from .models import Product def product_list_view(request): queryset = Product.objects.all() context = { "object_list": queryset } return render(request, "products/product_list.html", context) # ------------------------------------------------------------ # class UpdateProductView(UpdateView): model = Product template_name = 'products/product_update.html' fields = ['title', 'image', 'description', 'price', 'summary', 'featured'] product_list.html {% extends 'base.html' %} {% block content %} {% for instance in object_list %} <p> {{ instance.id }} - <a href="{{ instance.get_absolute_url }}">{{ instance.title … -
Auto complete jquery not working using Django framework
I am trying to perform an autocomplete for a search box but am not getting any requests back when typing. Index.html Url.py Views.py -
Is this the correct usecase for Django/Pythong > WebApplication
I really hope this is the right place for this question or else please lmk what i can change. Also, I'm pretty much a total beginner in programming, did only a little bit of C in Uni. I recently started my Master Thesis and my task is to program a Web Application in Python/Django based on a Matlab program, which already exists. It includes a lot of user-input and uses it to calculate and visualize stuff (mostly simple formulas), but it includes plenty of tabs and user-profiles. The question is now if this is even the right way to go. I just now learned that Matlab offers its own WebApp Server (Which I'm not quite sure yet how to qualify for). Also i'm not really sure if Django is even the right Framework to use... I would be very happy if anybody could point me in the right direction here :) If you need any additonal information, please let me know, i'll do what I can. Cheers -
'str' object has no attribute 'get' error; in Django template when using dictionary
I am trying to retrieve some values from a dictionary in my template, so I defined the following template tag @register.filter('get_value_from_dict') def get_value_from_dict(dict_data, key): if key: return dict_data.get(key) and use it as follows {% for item in query_ %} <td>{{ mydictionary | get_value_from_dict:item.id }}</td> {% endfor %} However it gives me the following error: 'str' object has no attribute 'get' I made sure that I am passing an actual dictionary and not a string so this works fine in my template {% for key, val in mydictionary .items %} <p>{{ key }}</p> <p>{{ val }}</p> {% endfor %} which has some values like: sub_ITWGauJH5czYPL False sub_ITWEjGl6PTLXBN True I was wondering where can be my error? -
Django user subscribe user relation
I`m creating a simple blog now, and the main problem is to create a relation between Users. I use a default django User which should subscribe another user who is an author of post. I have only one Post model in my app class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=128) content = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) seen = models.ManyToManyField(User, related_name='blog_posts', blank=True)