Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST method not allowed in custom viewsets
if I am going to add products to cart I get error. POST method not allowed views.py class CartViewSet(viewsets.ModelViewSet): queryset = Cart.objects.all() serializer_class = CartSerializer @action(methods=['post', 'put'], detail=False) def add_to_cart(self, request, pk=None): cart = self.get_object() try: cart.user = self.request.user product = Product.objects.get(pk=request.data['product']) quantity = int(request.data['quantity']) except Exception as e: print(e) return Response({'status': 'fail'}) if product.inventory <= 0 or product.inventory - quantity < 0: print('There is no inventory in store') return Response({'status': 'fail'}) existing_cart_item = CartItem.objects.filter(cart=cart, product=product).first() if existing_cart_item: existing_cart_item.quantity += quantity existing_cart_item.save() else: new_cart_item = CartItem(cart=cart, product=product, quantity=quantity) new_cart_item.save() serializer = CartSerializer(cart) return Response(serializer.data, status=status.HTTP_201_CREATED) It works when i give the url like that carts/1/add_to_cart here I am giving my cart id but in my case it is wrong because when user is created cart is also created that's why user and cart ids are same. I do not nedd to give cart id in the url because I am putting token in Authorization section in Postman, from that it should detect which user is sending post request. It is shown above that I added cart.user=self.request.user with it still it is not working. How can I solve this issue? Any help would be appreciated) -
Django - force user password reset/expiration
I'm stuck at this issue now for a good few hours. I've implemented all the standard password change, reset, etc functionalities which are built in with django.contrib.auth.forms. The task I want to accomplish is to force users to regularly change their passwords. Which leads to the following issues: If I redirect them to the reset workflow it will change the password and I have not found a way to update my password_changed timestamp in my custom user model since the functionality is built into django. I could redirect them to the password change view (which also uses a builtin form), unfortunately if the user is not logged in (which would be counter productive in this case) the user attribute in the request is "None" Maybe I'm thinking too complicated, can someone give me a hint whats the easiest way to implement this?? -
django get data from api with ajax
I was trying to get some information from API using ajax. I was able to post data but I was unable to get all the data from the server. I am new in the Django environment, though i have tried some references. I was wanted to get the data from the server using the API that I provide and show those data by using ajax get call. References that I have followed: 1.Django Ajax Jquery Call 2.https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html 3.https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html My code for get call: $.ajax({ type: "GET", url: "/save_composition", dataType: "json", success: function(data) { alert(data) }, error: function(xhr, textStatus) { alert("error.."); }}); Url section : path('restore_composition/', views.restore_composition, name='restore_composition') Views.py: def restore_composition(request): data = SaveComposition.objects.all() return render(request, 'index.html', context={'data': data}) -
Meaning of some errors while hosting django application on Cloud Foundry
While trying to host my Django application on Cloud foundry using Gunicorn, my application will be hosted correctly on the URL, but when I see the logs by doing cf logs --recent I see some errors: 2019-10-18T17:06:36.85+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [9] [INFO] Starting gunicorn 19.9.0 2019-10-18T17:06:36.86+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [9] [INFO] Listening at: http://0.0.0.0:8080 (9) 2019-10-18T17:06:36.86+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [9] [INFO] Using worker: sync 2019-10-18T17:06:36.86+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [68] [INFO] Booting worker with pid: 68 I want to know what are these errors. And, after these errors also the application is hosted and is up. -
How to implement protected file download with requests and authentication in django
I have a django app where I can upload files. I show my files in an API. Like so: class FileCollection(models.Model): name = models.CharField(max_length=120, null=True, blank=True) store_file = models.FileField(upload_to=upload_file, null=True, blank=True) creation_date = models.DateTimeField(null=True, blank=True) class FileDownloadAPIListView(ListAPIView): """Lists all files. """ queryset = FileCollection.objects.all() serializer_class = FileCollectionSerializer Later I will implement different queries to get specific files. I'd like to download these files from a script using python without the need to open up a browser or anything like that. I want to make an authenticated API call with requests that gets my file and then saves it to the local computer. The problem is that my files need to be private and only authenticated users should be able to download it. For my other APIs I am using JWT token authentication. My question now is: How do I implement this? Do I a) Save my files in S3 and make an API call to that URL somehow authenticating me with my AWS credentials? b) Save my files somewhere in my PostgrSQL database and get everything from there with an authenticated API call using JWT. c) third option I didn't consider Also if I use a, b or c how … -
"ModuleNotFoundError: No module named 'django'" when trying to deploy Django server on Azure
After I tried to deploy my Django website on Azure, I got an error saying: ModuleNotFoundError: No module named 'django' I added a requirements.txt in the root directory of my Django project, am I missing anything else? I've tried to install Django from Kudu BASH but it gets stuck on "Cleaning Up". Here is the full error: https://pastebin.com/z5xxqM08 I built the site using Django-2.2 and Python 3.6.8. -
What are the skills and steps required to do an interactive info chart like this?
As a beginner in python and with an interest in data visualisation, I am intrigued by this https://opportunityatlas.org It inspires me to use it as a guide to break down what to learn and skills to acquire to learn to do something similar. I wonder is the map done using matplotlib? or is it HTML/CSS? Is it Django or Flask for the interactive web interface? My knowledge at the moment is too limited to know what's out there or any terms to search on. If anyone knows what are the steps and skills to acquire for developing an application like this, can you share a general guideline? Or is there any tutorial out there? Thanks. -
How to set on_delete=models.CASCADE default in python 3?
Currently I am working to convert my python2 Django web-project into python 3. My project contains lots of models.py files so I have to add manually on_delete=models.CASCADE in all files where I have set default it in python 2. Now there are around more than 2000 instances where I need to do same practice. Is there are any hacks or possible solution available so that I can set on_delete=models.CASCADE in my all models instantly. -
Debugging Javascript in a Python Django project
I have a Python/Django project and am currently trying to find a way to debug the Javascript components on the site using VSCode. I've done some research and the only method I can find is to use the paid version of PyCharm. Does anybody know how to configure VSCode to do this? -
alternative to wkhtmltopdf to render pdf with javascript charts and bootstrap classes
I have a web application and I use the tool wkhtmltopdf to perform pdf exports. I am using wkhtmltopdf version 0.12.4 with unpatched QT (minimal version). I want to add a footer to the pdf pages and I saw that the wkhtmltopdf version with patched QT support this operation with the flag --footer-html. Unfortunately I noticed that the css and js engine under this version create some problem in rendering my html pages: First of all there are problem with the grid system in Bootstrap v > 4.1 Then also the javascript chart in my page are no more rendered in the pdf with this version of wkhtmltopdf So, is there an alternative to wkhtmltopdf that allow me to export to pdf my web pages ? My project is written in django / javascript so I would prefer a python of javascript tool. I also tried pdfkit but I discart it because I saw it is based on wkhtmltopdf , and django-weasyprint but I discarted because it does not support javascript (so my charts are not rendered). Finally the tool should allow me to connect to the web page passing cookies or similar, because login is required to access the … -
How to integrate SaaS result which needs to create multiple URLs at the website end?
Assume there is a SaaS product where user can create multiple pages and content at the dashboard. Now we wish to make a plugin system where we can let the website owner just plug it and display all the content. Now we are facing problem where we don't have an effective way to automatically create the different URL as required by the backend content. What is the best way to do it? Is there any workable example of this? -
Django: int() argument must be a string, a bytes-like object or a number, not 'Post'
I am getting this error for a long time and I tried to solve with some forums but I don't find the gap. Here is my Models.py: class Post(models.Model): def show_article(request, id_post): article= Post.objects.get(id=id_post) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): nick = form.cleaned_data['nick'] message= form.cleaned_data['message'] email = form.cleaned_data['email'] rating = form.cleaned_data['rating'] to = article #comentario = Comment(nick=nick, email=email, message=message, rating=rating, to=to) comentario = Comment() comentario.nick=nick comentario.email=email comentario.message=message comentario.rating=rating comentario.to_id=to comentario.save() send_mail( "Thanks for your comment %s" % nick, "Here is a copy of your message: \n %s" % message, 'noreply.ibai@gmail.com', [email], fail_silently=False) return redirect('/news/%i' %id_post) else: form = CommentForm() context = {'articulo': article, 'form':form} return render(request, "cnn/articulo.html", context) And: class Comment(models.Model): nick= forms.CharField(max_length=10) email= forms.EmailField(max_length=30) message= forms.CharField(max_length=600) rating= forms.ChoiceField(choices=LIKE_CHOICES) to_id= models.ForeignKey(Post, on_delete=models.CASCADE) class CommentForm(forms.Form): nick= forms.CharField(max_length=10) email= forms.EmailField(max_length=30) message= forms.CharField(max_length=600) rating= forms.ChoiceField(choices=LIKE_CHOICES) The problem came when I do 'migrate', because with de makemigrations the error dont occured. This is the log from console: (env2) C:\Users\ibaig_vi6j6bo\AppData\Local\Programs\Python\Python37-32\.projects\pruebasDjango>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying polls.0013_comment_to...Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\ibaig_vi6j6bo\AppData\Local\Programs\Python\Python37-32\.virtualenvs\env2\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() … -
Djnago channels security
I'm studying django channels and there's this problem: let's say I have a routing channel: websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<id>[^/]+)/$', ChatConsumer), ] It turns out that anyone who knows the channel number can listen to messages that go to this address. Maybe you can send data (for example, a token) sometime during the socket connection? Thank you. -
Best way to save data to a Django project from serverless functions
I'm currently trying to migrate some of the regular periodic tasks we have running from our main app server (Django) to serverless functions. More or less all these tasks work the same way: Query some data from the Postgres DB (Using the Django ORM) Manipulate the data Save the data (Also using the Django ORM) What would be the best way to replicate saving the data, I've got a few options I've thought about: Bundle the Django project with the serverless function and just use the Django ORM Direct connection to the Postgres DB Perhaps create a POST API endpoint on the main server that can be used to send the data from the function to the main app server? Would love to know what everyone thinks or other ideas you think are better? -
If condition for having checkbox checked only working the first time in Flask?
I have a table with products and a checkbox which tells if the user likes the products or not which is the products.like = {1,0} variable. I have a hidden button and a checkbox button such that both 1 and 0 state of the checkbox will be posted to the application. {% for product in products %} ... <td>{{product.like}}<input id = "h" type="hidden" name="checkbox:{{product.index}}" value={{product.like}}><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value" {% if product.like == 1 %} checked {% else %} {% endif %}></td> From the application I then update the product.like if the user has clicked the checkbox. ¨ app.py @app.route('/', methods = ['GET', 'POST']) def index(): name = None checkbox_count = 0 if request.method == 'POST': for key in request.form: if key == 'search': name = request.form['search'] if name is not None or name != "": query_product = Products.query.filter(Products.productname==name).first() if (query_product is not None) and (query_product not in product): product.append(product) if str(key).find('checkbox') != -1: #Check if key is a checkbox value. company[checkbox_count].like = request.form[key] #Update the like variable checkbox_count = checkbox_count+1 return render_template('index.html', products = product) The firs time I load the table, the correct checkboxes (the ones where product.like == 1) are checked in, but when I press the "update" button, … -
Django media file not found
Media file is not getting. urls.py added the below codes. from django.conf.urls.static import static from django.conf import settings urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py configured like below. STATIC_URL = '/static/' STATICFILES_ROOT = os.path.join(BASE_DIR,'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') profile.html these are html code. {% extends 'base.html' %} {% block main %} {{object.email}} {{request.user}} <img src="{{object.profileimage.image.url}}"> {% endblock %} Error code at console Not Found: /media/profile/1/function_uuid4_at_0x7fbf37ce42f0.jpeg [18/Oct/2019 10:01:45] "GET /media/profile/1/function_uuid4_at_0x7fbf37ce42f0.jpeg HTTP/1.1" 404 3421 -
Installing webpack_loader (webpack-template-loader) gives attribute error on assignment_tag
I'm trying to add webpack-template-loader to my project (djang=2.2.1, django-webpack-loader===0.2.4, webpack-bundle-tracker=^0.4.3,webpack=^4.41.2). To the best of my ability, I've followed the instructions here. My settings.py looks like this: INSTALLED_APPS = [ ... 'webpack_loader', ] # webpack loader BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': False, 'BUNDLE_DIR_NAME': 'assets/', 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE': [r'.+\.hot-update.js', r'.+\.map'] } } in my package.json I have the following: { ... "scripts": { "build": "webpack --config ./webpack/prod.config.js", "build-dev": "webpack --config ./webpack/dev.config.js --display-error-details" }, "dependencies": { "webpack": "^4.41.2", "webpack-bundle-tracker": "^0.4.3", "webpack-cli": "^3.3.9" } } and running npm run build-dev correctly builds my bundle without error. On adding 'webpack_loader' to INSTALLED_APPS my server stops turning and i get the error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/local/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line … -
Why aren't images being saved in my Django upload form?
I'm having trouble getting my image field to upload correctly with Django. I'm using crispy forms, and all other elements on the form and page work fine. The image field does not produce any errors error or save. I can add the image through admin just fine, it only fails on my crispy form. views.py class CarCreate(generic.CreateView): model = Car slug_field = 'id' slug_url_kwarg = 'car_create' template_name = 'showroom/car_create.html' form_class = CreateCarForm success_url = None def get_context_data(self, **kwargs): data = super(CarCreate, self).get_context_data(**kwargs) if self.request.POST: data['images'] = CarImageFormSet(self.request.POST) else: data['images'] = CarImageFormSet() return data def form_valid(self, form): context = self.get_context_data() images = context['images'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if images.is_valid(): images.instance = self.object images.create() return super(CarCreate, self).form_valid(form) def get_success_url(self): # return reverse_lazy('showroom:cars', kwargs={'slug': self.object.id}) # Throws an error return reverse_lazy('showroom:cars') forms.py class CreateCarForm(ModelForm): class Meta: model = Car exclude = ['seller', 'id'] def __init__(self, *args, **kwargs): super(CreateCarForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.form_enctype = 'multipart/' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('manufacturer'), Field('car_model'), Field('model_year'), Field('transmission'), Field('mileage'), Field('description'), Field('price'), Field('drivetrain'), Field('engine_displacement'), Field('forced_induction'), Fieldset('Add Images', Formset('images')), HTML("<br>"), ButtonHolder(Submit('submit', 'Save')), ) ) formset.html {% load crispy_forms_tags %} <table> {{ formset.management_form|crispy … -
Unauthorized response to POST request in Django Rest Framework with JWT Token
I am building a REST API with Django Rest Framework. I currently have an issue where some of my endpoints return HTTP 401 Unauthorized, whereas the vast majority of my endpoints return correct responses. For authentication I am using JWT tokens with djangorestframework-simplejwt. I've configured Django to use token auth with djangorestframework-simplejwt. # rest framework config settings REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', # 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ], The vast majority of my endpoints return valid data when I pass a valid access token in the request. If I do not send a valid token, I receive a HTTP 403. On the other hand, I have some custom API views which return a HTTP 401 regardless of whether I pass a valid token or not. I have included the code to one of my problematic views below. class CheckDifferentialView(generics.GenericAPIView): permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] serializer_class = QuizDifferentialSerializer def post(self, request, *args, **kwargs): """ A function to check a quiz question and to update a user's record of questions answered """ print(request.META) if 'answer' not in request.data: return JsonResponse({'Error': 'answer not found in request'}, status=status.HTTP_400_BAD_REQUEST) answer = get_object_or_404(Differential, pk=request.data['answer']) serializer = QuizDifferentialSerializer(answer) if answer.is_correct: pass # … -
Django REST - HttpOnly cookie
It is a simple question but I just cannot find the answer. I want to have a fully safe way of storing token in my FE Those are the current steps for login + other "login required" actions SPA site requests a token (username and password) OAuth responses with a token SPA stores that token in a HttpOnly cookie Logged in SPA site requests a data from the BE (cookies are sent with the request) and here comes the problem Django gets all of the cookies EXCEPT those that are with HttpOnly flag How can I fix this? -
How to obtain cleaned_data from a FormSetView (django-extra-views)
I cannot see how to trigger and obtain the cleaned_data from my FormSetView. With a django formset, I would call is_valid() on the formset within a POST'ed response, but not sure how to do that here. Examples in documentation do not show this, afaics. I've implemented exactly as per the example in django-extra-views documentation. I already have a ModelFormSetView working fine although the DB update is automatic in that case. However, in this case of non-model implementation the cleaned data necessarily needs to be massaged into a different format for DB storage. My view (called from the url entry): class TemplateFSView(FormSetView): template_name = 'template_season.html' form_class = TemplateForm success_url = 'tee/home/' def get_initial(self): # initial data is a pre-load test for now... return [{'commence': '07:30', 'finish': '22:00', "spacing": "10"] def formset_valid(self, formset): # do whatever you'd like to do with the valid formset print('How do I get here?') return super(TemplateFSView, self).formset_valid(formset) Form: class TemplateForm(forms.Form): commence = forms.CharField(required=True, label='first tee-time') finish = forms.CharField(required=True, label='last tee-time') spacing = forms.CharField(required=True, label='tee spacing') Template: <form method="post"> {% csrf_token %} <table> {% for form in formset %} {% if forloop.counter == 1 %} <thead> <tr> <th scope="col">{{ form.commence.label_tag }}</th> <th scope="col">{{ form.finish.label_tag }}</th> <th scope="col">{{ form.spacing.label_tag … -
Django Grant permission to Foreign key objects
I have an Image model with a foreign key to Album. A User can have edit or read only permission on Album. How do users with edit Album permission, also edit Images under this Album? Is there a simple way in Django to grant User permissions over foreign key objects? -
I am not able to write a file in NFS which has some chinese character in file name
Basically, when user uploads the file I am writing that file into NFS. But it gives an error 'ascii' codec can't encode characters in position 28-32: ordinal not in range(128) I have tried to install Chinese locale and set it but it is not working I am taking the file name as this but it is not working file_name = file_name.encode('ascii').decode('unicode-escape') -
React-admin turning off reliance on X-Total-Count
I expected React-admin to work out the box with Django Rest Framework, like its website implied but my experience is that it doesn't. It has been a time consuming task trying to set custom headers to fit react-admins requirement for X-Total-Count header for every response. Django Rest Framework prefers to put the count in to the json response it seems. Does anyone know how to read this information from the json instead? It seems logical to me to set an option in react admin instead of rewriting the middleware with Django or other rest frameworks. -
Debugging git packages given in requirement.txt file for application hosted on Cloud Foundry
I am hosting a Django application on Cloud Foundry. In requirement.txt file, I am adding my git code (as a package). I have written some print statements to debug my package. where will I see those print statements. Or How Can I debug a git package I am adding in requirement.txt file. I need to check where my code is failing. I wanted to use a git package in my application. I added it in requirement.txt file and hosted my application on Cloud Foundry. But that package is failing somewhere. So, I wanted to debug where it is failing. I downloaded the package and added print statements in the package code. How can I see those print statements. Or what is the way I can debug, where that package is failing.