Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Forbidden (CSRF cookie not set.) when sending POST/DELETE request from Vue.js to Django
I have been trying for a while to send a POST or DELETE request from my Vue front-end to my Django backend. I am running Vue.js on my localhost:3000, and Django on localhost:8000. I have set up CORS with django-cors-headers, and I am able to GET requests. However, once I try to DELETE or POST, I get this error: Forbidden (CSRF cookie not set.) I understand, that I need to pass a CSRF token in my request's header, which I have: deleteImage() { const url = this.serverURL + 'images/delete/' + this.image_data.pk; const options = { method: "DELETE", headers: {'X-CSRFToken': this.CSRFtoken} }; fetch(url, options) .then(response => { console.log(response); if (response.ok){ // if response is successful, do something } }) .catch(error => console.error(error)); } I obtain this.CSRFtoken from a GET request, and the token is the same if I use the approach shown in Django docs. My Django settings.py looks like this: rom pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '***' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = … -
How to Show Average of Star Rating in django
I want to show an Average 5 Star rating in Django. Like in the picture below. In the above image, there is an average rating of all users for a specific product and plus the Count of reviews. Hence to store the rating to DB I used something code like this. views.py def product_detail(request, id): product_detail = Product.objects.get(id=id) review = Review.objects.filter(product = product_detail) return render(request, 'detailpage/productdetail.html', {'product_detail':product_detail, 'review':review}) review.html <div class="container col-sm-7"> <form action="/product_review"> <input type="hidden" name="product_id" id="product_id" value="{{product.id}}"> <h4 style="font-weight:bold" class="mt-5">Create Review</h4> <hr> <h5 style="font-weight:bold">Overall Rating</h5> <div class="stars"> <input class="star star-5" id="star-5" type="radio" name="rate" value="5" /> <label class="star star-5" for="star-5"></label> <input class="star star-4" id="star-4" type="radio" name="rate" value="4"/> <label class="star star-4" for="star-4"></label> <input class="star star-3" id="star-3" type="radio" name="rate" value="3"/> <label class="star star-3" for="star-3"></label> <input class="star star-2" id="star-2" type="radio" name="rate" value="2"/> <label class="star star-2" for="star-2"></label> <input class="star star-1" id="star-1" type="radio" name="rate" value="1rate"/> <label class="star star-1" for="star-1"></label> </div> <h5 style="font-weight:bold">Add a headline</h5> <input type="text" name="subject" class="form-control" id="inputDefault" autocomplete="off"> <br> <h5 style="font-weight:bold">Add a written review</h5> <textarea class="form-control" name="comment" id="exampleTextarea" rows="3"></textarea> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> models.py class Review(models.Model): user = models.ForeignKey(User, models.CASCADE) product = models.ForeignKey(Product, models.CASCADE,null=True, blank=True) subject = models.CharField(max_length = 100, null=True, blank=True) comment = models.TextField(max_length=250, null=True, blank=True) rate = models.IntegerField(default=0) … -
Next parameter in URL does not redirect to the right page with Django
I have a Django app with an authentication system, where people need to ask access to an admin before being able to access the website. Admins receive an email with a link in it to accept of refuse the access, and you need to be logged in to do so. This is the function that is called when they click the link. @login_required() def valid_access(request): if (request.user.groups.filter(name='access_validators').exists()): temp_link = request.GET['temp_link'] demand = Demands.objects.get(temp_link=temp_link) if demand.status != 'validation': return render(request=request, template_name='index.html', context={'message': 'The request has already been ' + demand.status}) else: context = { 'firstname': demand.firstname, 'lastname': demand.lastname, 'email': demand.email, 'organisation': demand.organisation, 'motivations': demand.motivations, 'temp_link': temp_link } return render(request, 'validation.html', context) else: return render(request=request, template_name='index.html', context={'message': 'You don\'t have the right to do that.'}) My urls.py file : urlpatterns = [ path('', include('django.contrib.auth.urls')), path('valid_access', views.valid_access, name='valid_access'), ] If the admin is already logged in, it works fine. If the admin is not logged in, it redirect him to the login page as expected. The link looks like this : https://my.url.com/users/login/?next=https%3A//my.url.com/users/valid_access%3Ftemp_link%3DnAHWc7G3FvG%40Fj But once he's logged in, it does not redirect him to the validation page, but to the LOGIN_REDIRECT_URL I have set in the settings. My login.html looks like this {% extends … -
Is it Possible to Integrate React in an Existing Django Project's Template? Only for a specific template file (Like as- only in cart.html)
I have a complete Django Project, which is ok with all it's features and functionalities. But Now, I want to implement REACT in that project only for the CART Functionality. I want to use react only on cart.html template file. I know how to implement REACT with Django. But I don't know how to do it only in a particular html template file. Have any idea to show it in Django default port?? -
pymongo get relational object query issue
here is code get_category = db.interests.find({"interestStatus": int(page)}).sort([("sequenceId", -1)]) here is collection object {"_id":{"$oid":"60e01893d4cdee8f520b8145"},"interestName":"test1234","interestActiveIconUrl":"","interestInactiveIconUrl":"","sequenceId":{"$numberInt":"59"},"backgroundImage":"","interestStatus":{"$numberInt":"1"},"interestStatusText":"delete","categoryId":{"$oid":"5e5e5fd9527f71283e4582c6"},"createdOn":{"$numberDouble":"1583243225300.9"}} want to get category data by pymongo 'categoryName': i['categoryId']['categoryName'], but getting server error -
How to receive authorization token in Django?
A third party application has send a token to my website http://www.example.com. How to check or print the authorization token? -
Django reload current page without using path
this is probably a noobie question. I'm working on a Django project, after a request, I reload the page using: return redirect('home') Is there anyway to reload the current page without writing the url path? I don't need to specify it, since the page I need to reload is the one that is actually open. Hope someone can help and sorry for easy english -
How to get the variable from api and define in Nginx config file
I am using a GET api in which there is a parameter which is dynamic(a variable). I want to get that variable and give it to my Django server, but how do I tackle this in Nginx as I have a static api location. The code where I am hitting the api: Here waterQuantity is variable that will be provided by the user. http.Response response =await http.get('http://192.168.0.110/openValveConst/$waterQuantity'); This is my Nginx config file right now: location /openValveConst/ { # why should i add / at the end 5000/ to make it work proxy_pass http://127.0.0.1:8000/openValveConst/?format=json proxy_set_header X-Forwarded-For $remote_addr; } Please suggest changes that I should do to make this work. -
OpenEdx Android and IOS application important dates tab not visible
I have a query related to important dates tab in ios and android application, they both are not working the and showing [Unknown error please try again later]. Then i have implemented waffle flags in django for course dates and it starts working on application but now the web is not working. Please help if any have gone through the problem please help. Attaching logs of my android application the log is redirecting to some localhost url but i am unable to find from where it is coming? Android Logs -
my django form is not saving the inputs in the admin panel
How do I style my django form to look like my frontend template originally was? I created my django form and it does not look good and it is not saving the inputs in the admin panel either. Could you tell me what I need to add in the code or what I'm doing wrong? models.py class Complaints(models.Model): user = models.ForeignKey(User, on_delete= CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.BooleanField(default=False) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title views.py: class ComplaintCreate(CreateView): model = Complaints form = ComplaintForm fields = '__all__' success_url = reverse_lazy('New') template_name = 'new.html' template: </div> <!-- Middle Container --> <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field"> {{form.title}} </div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <div class="Descr"> {{form.description}} </div> <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> <button type="submit" class="btn btn-secondary save-btn" value="submit"><i class="fas fa-save"></i> Save</button> </form> </div> forms.py class ComplaintForm(ModelForm): class Meta: model = Complaints fields = '__all__' exclude = ['user'] Also the site looks like this atm: How do I make it look like this?: -
Reference static folder in view
How should I reference an app's static folder from within the app's view? At the moment I am doing the follow which works: background = Image.open("/home/me/django_apps/new_app/static/background.png").convert("RGBA") So I have a static folder in the root folder for my app. -
Django: Get each user Invoices, Expenses, Withdrawals. (ORM) relationship
I've been stuck for a couple of hours, and can't figure out the correct way to do it. So basically I know that looping is not a really good practice, because if we would have a lot of users, the system would start time outing. So my idea is to pick the correct way to get the things that I need. This is our core scheme: I need to make this kind of 'table', and these are the things that I need: This is the thing that will be displayed in our Front-End, so for now, I only need to collect the correct data and pass it into our FE. We use celery tasks, so the timing is always set (Mondays at 6 PM for ex.) This is what I've tried so far.. for user in User.objects.all(): start_date = timezone.now() - timedelta(weeks=1) # How to loop correctly over every user and check for invoices?? invoices = InvoiceItem.objects.select_related('invoice', 'invoice__operation_ptr_id') # invoices[0].operation_ptr_id ??? The looping for user in User.objects.all() should probably be replaced to annotate. How can I make the relationship to get invoices, withdrawals, expenses? -
flask gateway equlivent in django
I'm setting up my Braintree web-hooks in Django, as Braintree docs says i have to add this method from flask import Flask, request, render_template, Response ... def webhook(): webhook_notification = gateway.webhook_notification.parse(str(request.form['bt_signature']), request.form['bt_payload']) # Example values for webhook notification properties print(webhook_notification.kind) print(webhook_notification.timestamp) return Response(status=200) everything is ok except i have no idea what gateway is, and I'm getting undefined name error my Django code @csrf_exempt def webhook(request): print("post:: ", request.POST) webhook_notification = gateway.webhook_notification.parse(str(request.form["bt_signature"]), request.form["bt_payload"]) print(webhook_notification.kind) print(webhook_notification.timestamp) return HttpResponse("Ok") -
django.db.utils.ProgrammingError: relation "xx" does not exist
I was trying to add a new column to a database table by using make migrations on Django, bit didn't work and I got some weird errors. Following advice on another SO post I used DROP TABLE to delete the table and start again. The problem is, now when I try to migrate the table it doesn't appear in my PostgreSQL database. When I check make migrations I don't get any changes to migrate suggesting it is synced. I have also run: python3 manage.py migrate --run-syncdb and still getting no luck. I'd appreciate any help. class UserVenue(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) user_list = models.ForeignKey(UserList, on_delete=models.CASCADE) class Meta: unique_together = ['user_list','venue'] For some reason I can still see the table in Django Admin but then get this error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/testingland/uservenue/ Django Version: 3.1.7 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'testingland', 'rest_framework', 'bootstrap_modal_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "testingland_uservenue" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "testingland_uservenue" ^ ) was the direct … -
How to pass object 1st Serializer to 2nd Serializer, 2nd Serializer to 3rd Serializer and 3rd to 4th
Hello everyone I'm new to the Django framework. I need to pass the 1st Serializer object to the 2nd Serializer, the 2nd Serializer to the 3rd, and the 3rd Serializer to the 4th Serializer. Here is my code URL : path('job/int:pk/sections/templates/', JobViewSet.as_view({'get': 'list'})) Here is the method **all_templates(self, request, *args, kwargs) inside this method I added JobDetailSerializer(job) and pass the job object. @action(detail=True, methods=["GET"], url_path='sections/templates') def all_templates(self, request, *args, **kwargs): job = self.get_object() serializer = JobDetailSerializer(job) return Response( { 'status': SUCCESS, 'message': 'Data Received Successfully', 'status_code': HTTP_200_OK, 'data': serializer.data } ) 1st Serializer: JobDetailSerializer class JobDetailSerializer(serializers.ModelSerializer): template = JobTemplateListAllSerializer() class Meta: model = Job fields = ('manufacturer', 'model', 'serial_number', 'registration', 'engine_designation', 'date', 'location', 'created_at', 'image', 'client', 'customer', 'technician', 'template') depth = 1 Up to above, it's working fine now. 2nd Serializer: JobTemplateListAllSerializer class JobTemplateListAllSerializer(serializers.ModelSerializer): sections = JobSectionStructureListAllSerializer(many=True) class Meta: model = JobTemplates fields = ['sections'] 3rd Serializer: JobSectionStructureListAllSerializer class JobSectionStructureListAllSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) templates = serializers.SerializerMethodField() class Meta: model = JobSectionStructure fields = ['id', 'access', 'section_master', 'templates'] read_only_fields = ('job_template',) depth = 1 def get_templates(self, obj): template_structures = JobTemplateStructure.objects.all().filter(job_section_id=obj.id, template_master__parent_id=0) new_template_structure = [] for template_structure in template_structures: job_template_structure = JobTemplateStructure.objects.all() sub_template_structures = job_template_structure.filter(job_section_id=obj.id, template_master__parent_id=template_structure.template_master.id) template_structure.sub_templates = JobTemplateStructureDataListAppSerializer(sub_template_structures, many=True).data new_template_structure.append(template_structure) return … -
Does django field update nullable columns if you add a default value?
Let's say I have a field: status = CharField(max_length=20, null=True, blank=True) Then, I change this field to: status = CharField(max_length=20, blank=True, default="GOOD") does that mean that every object existing in the table with status=None will be converted to status=GOOD? Does that mean I don't need to create an data migration file? -
how to find a dictionary element using Jinja
I have python dict object which I am passing to the template {'bla bla': 'lalala'}. I want to reach this object with Jinja {{ dict_name.'bla bla' }} or {{ dict_name.bla bla }} or {{ dict_name['bla bla'] }} but all this not working. What i need do? -
How to return a html code having text and image using Ajax?
I am working in Ajax, and I want to print a text and then print the image below of that text using ajax. In Ajax code, there is a live_image_update() function and I want it to return the value text <br> image on success. The Ajax code is: <script> var state = NaN $(document).ready(function(){ $("#contactForm").submit(function(e){ // prevent from normal form behaviour e.preventDefault(); // serialize the form data var serializedData = $(this).serialize(); $.ajax({ type : 'POST', url : "{% url 'BFS:contact_submit' %}", data : serializedData, success : function(response){ //reset the form after successful submit $("#contactForm")[0].reset(); // This will then call for the get request to update the id "myText" live_update(); live_image_update(); live_state_update() }, error : function(response){ console.log(response) } }); }); function live_image_update(){ $.ajax({ url: "{% url 'BFS:get_bfs_image_info' %}", type: 'get', // This is the default though, you don't actually need to always mention it success: function(data) { $(myimage).attr('src', data + '?' + new Date().getTime()); }, error: function() { alert('Got an error dude in live image'); } }); } function live_state_update(){ $.ajax({ url: "{% url 'BFS:get_bfs_state_info' %}", type: 'get', // This is the default though, you don't actually need to always mention it success: function(data) { state = data document.getElementById("mystate").innerHTML = state … -
Can anyone describe this error: inconsistent use of tabs and spaces in indentation and Syntax Error [duplicate]
This is the code that but I don't know why it's showing same errors every time. if response.method == "POST": if response.POST.get("save"): for item in ls.item_set.all(): if response.POST.get("C" + str(item.id)) == "clicked": item.complete = True else: item.complete = False item.save() elif response.POST.get("newItem"): txt = response.POST.get("new") if len(txt) > 2: ls.item_set.create(text=txt, complete = False) else: print("invalid") return render(response, "main/page.html", {"ls":ls}) -
Check if matching object exist with id and manytomany field in Django
I have model as shown below : class Product(AdcBaseModel): file_id = models.CharField(max_length=256, null=True, blank=True) channels = models.ManyToManyField(Channel, blank=True) While creating a new entry in this model, I wanted to check if entry already exist with the given file_id and channels. For ex. Suppose if I have entry in the Product as (Note:channels is ManytoMany field): id file_id channels 1 ID_1 [11,12] 2 ID_2 [13,14] 2 ID_2 [15,16] Now if again I enter the values iof file_id as ID_2 and channels as [15,16]. Then it should check if this entry already exist or not. For file_id I can do something like this.: Product.objects.filter(file_id="ID_2").exists() Anything by which I can check ManytoMany field in the same way? -
How to install MySQL-python package for my Django project?
I'm unable to install MySQL-python==1.2.5 version for python-2.7.10 for my Django(Django==1.11.5) project. So far Installed C++ compiler package for python(VCForPython27) and C++ Redistributable v-14.29. I even tried pip install mysqlclient, but I got the same error. The project was completed. So, I can't use new package instead of MySQL-python. DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality. Collecting MySQL-python==1.2.5 Using cached MySQL-python-1.2.5.zip (108 kB) Building wheels for collected packages: MySQL-python Building wheel for MySQL-python (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'D:\Work\VirtualEnv\archiver\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'c:\\users\\nsew1\\appdata\\local\\temp\\pip-install-g08uwq\\mysql-python\\setup.py'"'"'; __file__='"'"'c:\\users\\nsew1\\appdata\\local\\temp\\pip-install-g08uwq\\mysql-python\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'c:\users\nsew1\appdata\local\temp\pip-wheel-lpqnzn' cwd: c:\users\nsew1\appdata\local\temp\pip-install-g08uwq\mysql-python\ Complete output (29 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-2.7 copying _mysql_exceptions.py -> build\lib.win-amd64-2.7 creating build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-2.7\MySQLdb creating … -
Create Docker Service for Autoplotter Python Library
I want to create a docker service for Autoplotter , and want to show its output in iframe which I can later show in my django templates ? Is it possible if yes please need guideline. Thank you -
Requests_html scraper calls async in django: 'There is no current event loop in thread %r.'
I'm totally new to coding and need some advise: I'm trying to implement requests_html scraping function in my django project and when it gets to the scraping part it runs an async function and raises en error: r.html.render(keep_page=True, scrolldown=1) … self.browser = self.session.browser # Automatically create a event loop and browser … self.loop = asyncio.get_event_loop() … raise RuntimeError('There is no current event loop in thread %r.' How should I go about this to make it work? Here's the scraper code: def biltema(url): session = HTMLSession() r = session.get(url) r.html.render(keep_page=True, scrolldown=1) price = r.html.find('.price__sum') get_price = price[0].text if ',-' in get_price: l = len(get_price) price = get_price[:l-2] else: rev_price = list(get_price[::-1]) rev_price.insert(2, '.') price = "".join(rev_price) price = price[::-1] return price and here's my view: class AddNewProduct(View): def get(self, request, *args, **kwargs): form = NewProductForm() return render(request, 'add_product_form.html', {'form': form}) def post(self, request, *args, **kwargs): form = NewProductForm(request.POST) if form.is_valid(): l = form.cleaned_data['link'] s = form.cleaned_data['shop'] c = form.cleaned_data['category'] n = form.cleaned_data['name'] p = biltema(l) Products.create(name=n, category=c, price=p, link=l, shop=s) messages.info(request, 'Produkt został dodany do bazy') return redirect('/products/') else: return render(request, 'add_product_form.html', {'form': form}) -
Fill table using others tables in Django
I got three table with Table A linked to Table B and Table B linked to Table C Table A : id code name 1 GFLA2021L AC2020 2 GFLB2021A PM2015 ... Table B : id code_A code 1 GFLA2021L GFLA2021L1 2 GFLA2021L GFLA2021L2 3 GFLB2021A GFLB2021A1 Table C : id code_B number 1 GFLA2021L1 12 2 GFLA2021L2 41 3 GFLA2021A1 9 And I want a new table fill with that data for example : Table expected : id name number 1 AC2020 53 <---- 12 + 41 2 PM2015 9 But, I don't know how to do it in Django ... If someone can explain me how to create that table auto fill with data from these 3 tables for having what I except. -
django loads page very slow
I have a django template that is generating a tree view using parent and child categories. The code is slow by generating 100+ sql queries and using django-debug-toolbar showing lots of duplicates. I am working on making this more efficient, but also I would like to get some guidance. Should I use template tags to generate every category children? {% for tc in tb_terminal_categories %} {% if not tc.parent %} <li class="mt-2"> <span class="tree-span"> <a href="{% url 'terminal-management' %}?category={{ tc.category_name }}">{{ tc.category_name }}</a> <a class="tree-child" data-toggle="modal" data-target="#terminal-category-modal"><i class="fas fa-plus"></i></a> <a class="tree-child" href="{% url 'tb-terminal-category-delete' tc.id %}"><i class="far fa-trash-alt"></i></a> </span> <ul> {% for tcc in tb_terminal_categories %} {% if tcc.parent == tc %} <li> <span class="tree-span"> <a href="{% url 'terminal-management' %}?category={{ tcc.category_name }}">{{ tcc.category_name }}</a> <a class="tree-child" data-toggle="modal" data-target="#terminal-category-modal"><i class="fas fa-plus"></i></a> <a class="tree-child" href="{% url 'tb-terminal-category-delete' tcc.id %}"><i class="far fa-trash-alt"></i></a> </span> </li> {% endif %} {% endfor %} </ul> </li> {% endif %} {% endfor %}