Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django drag and drop ordering for with many to many relationship of table
ManyToMany admin.TabularInline to display related objects in the admin app, and it works great except I can't figure out what to set the "ordering" property to so it can sort by one of the cross-referenced field names. I used this module django-admin-ordering==0.9.0. -
DjangoCMS on Plugin update CSS are not loading
I am running a DjangoCMS application(3.5.2). When a CRUD operation happens to any of the plugins, the whole page turn into plane white loosing all the CSS. As per my research, I could learn that this is happening since the CMS default page reload is not happening. When dig more into CMS package, noticed that minified js has been used for the same which restrict me to customise the JS. Would be great if anyone can advice me what exactly needs to be done to fix this. -
How to save the selected options of a multi select drop down into a java script list?
How to save all the selected options of a multi select drop down, created using bootstrap, into a java script variable as a list? And further,how to make use of that variable in a python script else where? -
Ubuntu 18.04, Nginx, Gunicorn, Django - how to keep the .env file secure
I'm using django-environ for using separate .env files that store sensitive data. In the case of the server being hacked, the file would be accessible to the intruder. Also, from what I read on this post, any intruder that manages to hack into the app owner account or root has access to the process memory. What is the most secure option for keeping the .env file secure in this enviroment? -
What should be the correct approach to pass in primary key into URL?
Right now I am using Class-based delete view, and my URL contains two arguments which are the primary keys of my 2 models: Post and Lesson. However, I am encountering an "Attribute Error": Generic detail view LessonDeleteView must be called with either an object pk or a slug in the URLconf. These are my two models Lesson and Post: class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default = 'default0.jpg', upload_to='course_image/') description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(default = 0) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk' : self.pk}) class Lesson(models.Model): title = models.CharField(max_length=100) file = models.FileField(upload_to="lesson/pdf") date_posted = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('lesson_upload', kwargs={'pk': self.pk}) This is my URLs.py: path('post/<int:post_id>/lesson_uploaded/<int:lesson_id>', LessonDeleteView.as_view(), name='lesson_delete'), Right now this is how I am trying to insert the parameters in my html template: {% block content %} <div id="main"> <table class="table mb-0"> <thead> <tr> <th>Title</th> <th>Author</th> <th>Download</th> <th>Delete</th> </tr> </thead> <tbody> {% for l in Lesson %} <tr> <td> {% if l.file %} {{ l.title }} {% else %} <h6>Not available</h6> {% endif %} </td> <td>{{ l.post.author }}</td> <td>{% if l.file %} <a … -
How to improve search results in Django Haystack + ElasticSeach
I have used Django Haystack + ElasticSearch for my search page. I followed this tutorial : https://techstricks.com/django-haystack-and-elasticsearch-tutorial/ Now the search process is working fine. But there are lots of unwanted results in search page. For eg: Searched word : Anon Result Obtained :Anonymous, adit ,Billa (and all names) Required Result : Anonymous Searched word : TestName1 Result Obtained :TestName1, TestName2 ,TestName3 Required Result:TestName1 I need exact matches if it were present. When I searched , I came to know about SearchQuerySet. But I have no clue about how to add it , where to add it , how to change my urls.py to the above code. I also think the wrong results were also because of the EDGENGRAM field. So How do I change MINnGRAM AND MAXnGARAM? search_indexes.py from haystack import indexes class UploadFileIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True, indexed=True) FileName = indexes.CharField(model_attr="FileName") User = indexes.CharField(model_attr="User") def get_model(self): return UploadFileModel def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().Objects.all() urls.py url(r'^search/', include('haystack.urls'), name="haystack_search"), settings.py HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack_elasticsearch.elasticsearch5.Elasticsearch5SearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', }, } HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' I currently dont have anything in my views and forms related to search. How do … -
HTML head tag appears inside body tag after adding django to the project
Following html code worked as needed before adding django to it. I didn't change anything, but now when i execute it, it has indent on the top of the page and head tag appears inside body tag in chrome. I tried to change position of some of the django syntax, but it didn't change anything. Here is the output of the code {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name = "viewport" content="width=device-width"> <meta name="description" content="Help Pets. We care about animals."> <meta name="keywords" content="charity, foundation, help pets, adoption"> <meta name="author" content="Irina Gorbacheva"> <title>Help Pets | Home page</title> <link rel="stylesheet" href="{% static 'style.css' %}"> </head> <body> <header class="header"> <div class="container"> <img src="{% static 'imgs/footprint.png' %}"> <div id="logo"> <h1><span>Help</span> Pets</h1> </div> <div> <button id ="popupclick">Donate</button> </div> <nav id="navbar" class="topnav"> <a href="{% url 'home' %}" id="cur">Home</a> <a href="{% url 'help' %}">Help</a> <a href="{% url 'adoption' %}">Rehoming</a> <a href="{% url 'reports' %}">Reports</a> <a href="{% url 'about' %}">About us</a> <a href="javascript:void(0);" class="icon" onclick="responsive()"> <svg width="30" height="30"> <path d="M0,5 30,5" stroke="#fff" stroke-width="5"/> <path d="M0,14 30,14" stroke="#fff" stroke-width="5"/> <path d="M0,23 30,23" stroke="#fff" stroke-width="5"/> </svg> </a> </nav> </div> </header> {% block content %} {% endblock content %} </body> </html> -
i can read the excel file and am showing that data in view page but i want to store that data in database and how to create rest api for this
here it is my code plz help me to do this am a beginner of this Django this is views.py from Django.shortcuts import render import openpyxl from .models import FileFieldForm def index(request): if "GET" == request.method: return render(request, 'well/index.html', {}) else: FileFieldForm = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(FileFieldForm) # getting all sheets worksheet = wb.sheetnames print(worksheet) excel_data = list() # iterating over the rows and # getting value from each cell in row for sheet_name in wb.sheetnames: worksheet = wb[sheet_name] for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) excel_data.append(row_data) return render(request, 'well/index.html', {"excel_data": excel_data}) -
User Feedback through Django Email
I have an app, in which the main User adds a sub user and sends him an email. I want the sub user to have a button in the email template that would lead him/her to a Feedback form. That feedback form's url must have the user's name in it as it gives a personal touch. But I am not understanding how do I save the feedback data. I will create a scenario to make you guys understand better. There is a main user Chris, Chris adds a sub user Leon in his email list. (P.S both are R.E bad asses). Chris sends an email to Leon, Leon will receive the email and if he want he can give a feedback by clicking the feedback button in email. If Leon clicks the button he will be redirected to a page where the url could be something like this (www.feedback/Leon.com), there will be form where Leon will add his review and submit. The problem is how do I save Leon's information in the sub user model and his review in the feedback model. models.py class FeedBack(models.Model): feedback = models.TextField('Feedback') user_feedback = models.ForeignKey(PersonData) class Meta: verbose_name = ("Client FeedBack") verbose_name_plural = ("Client … -
Do i have to install django again when i create a new project directory?
I am setting up a new project. I have installed virtual environment. But Do I have to install django again in that directory?? -
Django get client computer user name in view.py
To simplify my question. Client Computer Hostname = MyPC_011 Client Computer logged in username = user-A In views.py I want to use client machine logged in username(user-A) when user access django website page. This is my view.py def home_view(request): # Get IP address of client computer client_ip = request.META.get('REMOTE_ADDR') # Get Host Name of client computer client_host = request.META.get('REMOTE_HOST') return render(request, 'index.html') I get IP address by REMOTE_ADDR, REMOTE_HOST is empty, USER and USERNAME display server username. 'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PORT': '8000', 'REMOTE_HOST': '', 'CONTENT_LENGTH': '', 'SCRIPT_NAME': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_SOFTWARE': 'WSGIServer/0.2', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/', 'QUERY_STRING': '', 'REMOTE_ADDR': '192.168.5.107', ' How to get client machine logged in username when user access django website page? -
Bind two models
I need something like this: class Group(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField() torrents = # Link to torrents in group class Torrent(models.Model): id = models.IntegerField(primary_key=True) group = # Link to group name = models.TextField() hash = models.TextField(max_length=32) file = models.FileField(blank=True, null=True) and next in code: group = Group.objects.create(id=123, name="Test group") # some code... Torrent.objects.create(id=321, group=group, name="Test torrent", hash="hash") then: Torrent.objects.get(id=321).group.torrents.all() What I need to use? ForeginKey in Torrent to group and ManyToMany in Groups to torrents? -
How to get the next day's date in django.utils.timezone
I want to set the status of a task as due today, due tomorrow, overdue or upcoming if the date that the task is due on is today, yesterday (or before that) or tomorrow (or after tomorrow) This is what I do to compare today : if (timezone.now().date == k["due_on"].date) : task.status = "due today" I want to write similar logics for future or past something like this: if (k["due_on"].date == tomorrow) : task.status = "due tomorrow" and so on. Please help -
How to customize error messages in django rest framework?
How to customize error messages in django rest framework? I'm trying to do it clean. Without much code. But this is what I'm trying to do, it does not work. Thank you in advance for your attention. from rest_framework import serializers class serializerVenda(serializers.Serializer): tipo = serializers.CharField() amount = serializers.CharField( error_messages={ "required": "Amount cannot be empty." }) -
How to fill up a Django Field in a form which is dependent on another django dropdown value using AJAX?
I have a Django Form in which there is a dropdown field using ModelChoiceField in forms.py for the field which is retrieving data from a model's attribute. I want to pass the data through AJAX to my views and query another field's value using the data through Ajax. And send it back to the template such that this value should be automatically filled in another field of the same form. I am able to get data through the views and query from the desired model too. What should I do next to get the queried data to be placed onto the field in the form? I have already tried using this blog: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html But, he provides a method for using it for 2 dependent dropdowns and I tinkered the code according to my requirements but didn't work out. I also tried getting the value of dropdown through console but it doesn't show in the console whereas all the other input type fields show the value in the console. So, I am not sure whether the data of dropdown is getting through AJAX or not. Should the data of dropdown be visible in the console or not? AJAX of form_template.html {% … -
How to filter data displayed in a table in django?
I have a project where when a user enters a vehicle no, the database is filtered and a table containing that vehicle no and the information corresponding to is displayed. I further want to filter this displayed table, eg: if the user chooses to see quantity greater than 18kl, then the matching vehicle number with quantity greater than 18 is displayed. Also I want to hide the columns selected by the users as there are many columns. Can someone tell me how to do this in django, or suggest some better ways. (I am providing only the related code snippet.) forms.py class VehicleSearch(forms.Form): vehicl[![enter image description here][1]][1]e_no = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}), required=False) #filter form class Filter(forms.Form): capacity_grp = forms.ChoiceField(label='Show only', widget=forms.RadioSelect, choices=[('abv', '>18 kl'), ('blw', '<18 kl')], required=False) views.py def search(request): form_1 = forms.VehicleSearch() if request.method == 'POST' and 'btnform1' in request.POST: form_1 = forms.VehicleSearch(request.POST) if form_1.is_valid(): vehicle_no = form_1.cleaned_data['vehicle_no'] transport = models.Transport.objects.filter(vehicle=vehicle_no) my_dict.update({'transport': transport}) return render(request, 'search.html', my_dict) search.html /Vehicle form/ <form id="f1" method="POST"> {% csrf_token %} {{form_1.as_p}} <p style="padding: 10px;"><button class="myButton" name="btnform1">Search</button></p> </form> /*Table display*/ <div class="submain"> {% if transport %} <table id="transportation"> <thead> <th>Vehicle</th> <th>Carrier</th> <th>Location No</th> <th>MCMU</th> <th>Location</th> <th>Customer Code</th> <th>Zone</th> <th>Quantity</th> <th>RTKM</th> <th>KL* KM</th> <th>Amount</th> <th>Load</th> … -
Can we restrict any group to see search and filter option of user section in django admin?
I know how to apply search fields and filtering options in django admin but I want to allow them to only specific groups , any suggestion please...?? I have following code in my userAdmin. class UserAdmin(admin.ModelAdmin): list_display('username','department','dob','employee_id','email') search_fields = ('username','department','employee_id','email') list_filter = ('department',) -
Django how do I delete pictures on the server if the image on ckeditor is deleted
I have uploaded some images within the CKEditor, and uploaded images are stored on the server, when I delete the image on the editor, the image stored on the server is not deleted. Django 2.2, python 3.7, postgresql. my question: can I set it on ckeditor or on models? if can how to create a condition when the upload image is automatically deleted when removed on ckeditor? -
docker-compose , PermissionError: [Errno 13] Permission denied: '/manage.py'
After doing many research I didn't found any solution worked for me. I am trying to run command in docker-composer to start project with django-admin docker-compose run app sh -c "django-admin startproject app ." Every time I am getting the error: Traceback (most recent call last): File "/usr/local/bin/django-admin", line 10, in <module> sys.exit(execute_from_command_line()) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/startproject.py", line 20, in handle super().handle('project', project_name, target, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/templates.py", line 155, in handle with open(new_path, 'w', encoding='utf-8') as new_file: PermissionError: [Errno 13] Permission denied: '/manage.py' My docker file FROM python:3.7-alpine MAINTAINER anubrij chandra ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app COPY ./app /app RUN adduser -D dockuser USER dockuser My docker-compose.yml version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" I applied solution suggested in but it didn't worked [PermissionError: [Errno 13] Permission denied: '/code/manage.py' Ubuntu version : Distributor ID: Ubuntu Description: Ubuntu 18.04 LTS Release: 18.04 Codename: bionic -
How To Import CSV data in a product base application in django
I am working a product base application , where a master table name is "Product" and also some specific product tables. The Master Product Table related to other table by foreign key. Basically all the common attribute of products is belong to Master product table and specific attributes belongs to their own tables. So I want to upload data in tables by CSV files . So how to upload data from one CSV file to Multiple Tables ? -
Correct Offset on Canvas
I am attempting to draw on an HTML5 Canvas using some JavaScript from a PubNub tutorial. Currently the cursor will only draw on the canvas in the right position if the canvas covers the entire page, or in other words if it is at (0,0). It seems to be an issue with calculating the offest, and I have tried writing various offset variables into my code, but I have had no luck. Here is what I've currently got Javascript (function() { var canvas = document.getElementById('drawCanvas'); var ctx = canvas.getContext('2d'); var color = document.querySelector(':checked').getAttribute('data-color'); canvas.width = Math.min(document.documentElement.clientWidth, window.innerWidth || 300); canvas.height = Math.min(document.documentElement.clientHeight, window.innerHeight || 300); ctx.strokeStyle = color; ctx.lineWidth = '10'; ctx.lineCap = ctx.lineJoin = 'round'; document.getElementById('colorSwatch').addEventListener('click', function() { color = document.querySelector(':checked').getAttribute('data-color'); }, false); var isTouchSupported = 'ontouchstart' in window; var isPointerSupported = navigator.pointerEnabled; var isMSPointerSupported = navigator.msPointerEnabled; var downEvent = isTouchSupported ? 'touchstart' : (isPointerSupported ? 'pointerdown' : (isMSPointerSupported ? 'MSPointerDown' : 'mousedown')); var moveEvent = isTouchSupported ? 'touchmove' : (isPointerSupported ? 'pointermove' : (isMSPointerSupported ? 'MSPointerMove' : 'mousemove')); var upEvent = isTouchSupported ? 'touchend' : (isPointerSupported ? 'pointerup' : (isMSPointerSupported ? 'MSPointerUp' : 'mouseup')); canvas.addEventListener(downEvent, startDraw, false); canvas.addEventListener(moveEvent, draw, false); canvas.addEventListener(upEvent, endDraw, false); function drawOnCanvas(color, plots) { ctx.strokeStyle … -
How to upload and save image files manually on Graphene?
I am trying to upload and save image files using Django Graphene and axios. I uploaded files with no problem. I confirmed that files were transferred to the Django server. The problem is the image files do not get saved on the Django server. I uploaded images like const formData = new FormData(); const query = `...' formData.append('query', query); this.state.contents.map((content, index) => { formData.append('images['+index+']', { uri: content.image.uri, type: 'image/jpeg', name: 'image' + index + 'jpeg', }) await axios({ data: formData, I tried three ways to upload images. for file in info.context.FILES: image = models.Image(post=post, file=file) image.save() In this way, I can save Image models, but image files are nowhere. I tried to save the image files using a form. for file in info.context.FILES: form = forms.ImageForm(initial={'file': file, 'post': post}) if form.is_valid(): form.save() This invokes an error stating "Select a valid choice. That choice is not one of the available choices" I tried to save it with a formset as well. data = { 'images-TOTAL_FORMS': str(len(info.context.FILES)), 'images-INITIAL_FORMS': '0', 'images-MAX_NUM_FORMS': '10', } formset = forms.ImageFormSet(data, info.context.FILES, instance=post) if formset.is_valid(): formset.save() This formset just returns an empty formset and it does not save any data. How to upload and save image files manually … -
Creating a simple python calculation to show in the admin panel on a specific object record
I'm fairly new to python and am working on a new django project and want to display calculations in the admin panel for specific records, using the record data. This would also be replicated on the user interface (which is not built yet). I have learned the basic storing and manipulating of variables for other calculations made from basic user input. This is a little different as it is done within the admin panel. I am using PyCharm but PyCharm is telling me there are errors. I also used the link here to see if I could get this to work: https://www.reddit.com/r/django/comments/6xigr3/how_to_show_calculated_field_in_django_admin/ I realize the code below is not correct, but am also not sure if i'm referencing the variables correctly to access them from within the main function? How does defining this function change when used in the admin panel vs. the user interface? Thank you for any help on any questions above! # Create a class to calculate the volume by first converting inches to ft, then to cubic yd class Volume(models.Model): linear_ft = models.DecimalField('Length in feet: ', max_digits=200, decimal_places=2) depth_in = models.DecimalField('Depth in inches: ', max_digits=200, decimal_places=2) width_in = models.DecimalField('Width in inches: ', max_digits=200, decimal_places=2) # Convert … -
How do I know if Amazon successfully sent the email
In my django project, I am sending emails using Amazon-ses and some of the emails I have to send are critical. In this case I want to make sure that my email has been sent successfully, so that if not sent, I can resend it. Is there any way for me to know if the email was sent successfully? -
How to use django server work with Angular Universal to render the first page
https://angular.io/guide/universal I've read this. The example is for node express. I'm using django server, how to work with angular universal to render the first page.