Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - adjusting admin panel for users
I'm currently working on a Django project which will be available to use by several companies and their particular data about their clients. My question is if it is possible to adjust Django admin panel somehow, so that any user could log in (in this case the particular company worker) and have an access to admin tools, but only for the data related to his company (in this case the company clients)? Example: Worker of company X logs in and checks status of clients of his company, changes some data etc. At the same time worker of company Y logs in and does the same work with the clients related only to company Y. Both users see only clients related to their own company - they don't have access to other company's data. I've found something like this, but I'm not sure if it's appropriate to my situation :P -
How to configure django logger to have username in the format string WITHOUT using extra
How do I configure my logger to have request.user.username in the format string? I can do this with extra, but do not want to use it every time I want to log something. I have tried django_requestlogging but it wont import correctly to my settings... Is there a way to do this? -
Heroku: images don't show after some time
I've a Django APP hosted on Heroku. I upload some images within the admin panel, so the show in my site. First minutes/hours after upload they show fine. However, after a few hours they don't show anymore. I've to upload them again within the admin panel for them to show correctly. When in the HTML when no image appear: <img class="my_image_medium" src="/media/category/Artboard_1_PNG.png" alt="Stickers"> HTML with image re-uploaded: <img class="my_image_medium" src="/media/category/Artboard_1_PNG.png" alt="Stickers"> Django APP Settings: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^_67&#r+(c+%pu&n+a%&dmxql^i^_$0f69)mnhf@)zq-rbxe9z' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'stickers-gallito-app.herokuapp.com', 'stickersgallito.pe', 'www.stickersgallito.pe'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shop', 'search_app', 'cart', 'stripe', 'order', 'crispy_forms', 'embed_video', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'stickers_gallito.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'shop', 'templates/'), os.path.join(BASE_DIR, 'search_app', 'templates/'), os.path.join(BASE_DIR, 'cart', 'templates/'), os.path.join(BASE_DIR, 'order', 'templates/'),] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', … -
Django - Pass values from template to views file with Drop Down URL link options
I am currently redirecting the user to payment confirmation page if cash is selected from the dropdown list. <select class="custom-select " id="payment" name= "pay_method" onchange="SelFunction()" required> <option value=""> Select the Pay Method </option> <option value="credit card"> Credit Card </option> <option value="cash"> Cash </option> </select> <script> function SelFunction() { var x = document.getElementById("payment").value; if (x == 'cash') { window.location.href = "{% url 'payment_confirmation' %}"; } }; </script> This code is not posting any values to views files. I have tried with both request.POST and request.GET methods and none are working. Is there a way I can fetch the values from a template? -
How to keep database structure as much as possible same when switching git branches for Django project with docker containers?
We are developing a Django project using docker containers with multiple git branches. The problem we are facing is when we switch branches, automatic migrations are applied to all models when we restart the containers because of our docker configuration. We also don't want to apply manually migrations always on each change, that's why we included migration commands on the docker configuration. However, this causes some problems when we switch from a feature branch which is definitely ahead from the other one. The database structure is reverted and we are losing data. Is there any good way to keep database structure as much as possible same (superset) and not dealing with manual migrations when we switch from a feature branch to an outdated branch? Our docker configuration is as follows: version: '3.3' services: postgres: image: postgres:latest restart: always redis: image: redis:latest restart: always web: build: ./project command: bash -c "python manage.py makemigrations && python manage.py migrate --noinput && gunicorn project.wsgi -b 0.0.0.0:8000 --workers 16" volumes: - ./project:/app expose: - "8000" depends_on: - postgres - redis restart: always celery: build: ./project command: celery -A project worker -l info --concurrency=8 --max-tasks-per-child=1 volumes: - ./project:/app depends_on: - postgres - redis restart: always -
Close Bootstrap Modal On Submit with Django
I have been through pretty much every post on this forum and have not been successful at getting my modals to close after submission. data-dismiss does not work since it stops the submission before it starts. Using JavaScript code within the base html page also has not worked. Examples of posts that I have tried are here and here. My code is below. Any recommendations are appreciated. Submission is working. Modal just will not close. See modal "getAPI" below for example. <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap-theme.min.css"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> <div id="spacer"> </div> <div style="padding-left:20px;"> <button type = "button" class="btn" data-toggle="modal" data-target="#filetypeModal">Get Device Data</button> </div> <!-- File Type Modal --> <div class="modal fade" id="filetypeModal" tabindex="-1" role="dialog" aria-labelledby="filetypeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <form action="" method="post"> {% csrf_token %} <div class="modal-header" style="background-color: darkblue; color: white"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true" style="color: white">&times;</button> <h4 class="modal-title" id="filetypeModalLabel">File Types</h4> </div> <div class="modal-body" style="text-align: center;"> Choose file type to download.<br> <br> <label class="radio-inline"><input type="radio" name="choices" value="Excel" checked>Excel</label> <label class="radio-inline"><input type="radio" name="choices" value="CSV">CSV</label> </div> <div class="modal-footer" style="background-color: darkblue;"> <input type="submit" class="btn btn-primary" id="getAPI" value="OK" name="getAPI"></input> </div> </form> </div> </div> </div> <script … -
Extend django class from module in my view
I'm trying to extend a Django class providing from external library in my view in order to add some things. It's the first time I'm doing this kind of thing and I need some help. In my external module I have this class named EdqmThreadCreateView : class EdqmThreadCreateView(ForumPermissionMixin, ThreadCreateView): def __init__(self): super(EdqmThreadCreateView, self).__init__() self.form_class.base_fields['body'].label = 'Message' def get_initial(self): """ Returns the initial data to use for forms on this view. """ initial = self.initial.copy() # Get default topic topic_id = self.request.GET.get('topic', None) if topic_id: initial['topic'] = int(topic_id) return initial def form_valid(self, form): """ Save form if it is valid """ thread = form.save(self.request.user) url_redirect = get_absolute_url(thread) return HttpResponseRedirect(url_redirect) This class is in urls.py file of external module : urlpatterns = [ url(r'^forum/new', EdqmThreadCreateView.as_view(), name='forum-create-thread'), ... ] In my django app I would like to use the previous code, but I would like to add some things : change the url, add variables, ... In my views.py file, I wrote a very easy example to see if my class is called : from edqm.forum.views import EdqmThreadCreateView class KnowxThreadCreateView(EdqmThreadCreateView): def form_valid(self, form): print('this is the class used') And urls.py file : from .views import KnowxThreadCreateView urlpatterns = [ url(r'^forum/new', KnowxThreadCreateView.as_view(), name='forum-create-thread'), ] … -
pip install mass -> eror
pip install mass eror C:\WINDOWS\system32>pip install mass Collecting mass Using cached https://files.pythonhosted.org/packages/7b/54/97abbc40b4087748aecee98b19aecb4e1ca42a19cbce3b5b9984e91baa3f/mass-0.1.4.tar.gz Collecting distribute (from mass) Using cached https://files.pythonhosted.org/packages/5f/ad/1fde06877a8d7d5c9b60eff7de2d452f639916ae1d48f0b8f97bf97e570a/distribute-0.7.3.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\671D~1\AppData\Local\Temp\pip-install-1uxrpcwd\distribute\setuptools\__init__.py", line 2, in <module> from setuptools.extension import Extension, Library File "C:\Users\671D~1\AppData\Local\Temp\pip-install-1uxrpcwd\distribute\setuptools\extension.py", line 5, in <module> from setuptools.dist import _get_unpatched File "C:\Users\671D~1\AppData\Local\Temp\pip-install-1uxrpcwd\distribute\setuptools\dist.py", line 7, in <module> from setuptools.command.install import install File "C:\Users\671D~1\AppData\Local\Temp\pip-install-1uxrpcwd\distribute\setuptools\command\__init__.py", line 8, in <module> from setuptools.command import install_scripts File "C:\Users\671D~1\AppData\Local\Temp\pip-install-1uxrpcwd\distribute\setuptools\command\install_scripts.py", line 3, in <module> from pkg_resources import Distribution, PathMetadata, ensure_directory File "C:\Users\671D~1\AppData\Local\Temp\pip-install-1uxrpcwd\distribute\pkg_resources.py", line 1518, in <module> register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider) AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\671D~1\AppData\Local\Temp\pip-install-1uxrpcwd\distribute\ You are using pip version 19.0.2, however version 19.0.3 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. how to fix? -
Django - using different databases - should I use "using" or "db_manager"?
To select a specific database you write either: Object.objects.using('other_db')... or: Object.objects.db_manager('other_db')... Both seem to work completely fine. So what is the difference? -
How do you make all Django Admin fields with ForeignKey dropdown selections whose count is over 50 - Be ready only fields?
Example - If I have a FK field created_by to User model which has count of over 10000 User records. I want to check the count dynamically and set those dropdown fields as ReadOnly fields in Django Admin -
How to collect data from model into select tag
Model.py class techgroup(models.Model): Technology=models.CharField(max_length=50) def __str__(self): return self.Technology views.py def technology(request,id,*args, **kwargs): Technology = techgroup.objects.all() print(Technology) selected_item = get_object_or_404(techgroup, pk=request.POST.get('Technology_id')) # get the user you want (connect for example) in the var "user" techgroup.Technology = selected_item techgroup.save() context = {'Technology': Technology} return render(request, "analytics/radio.html", context) url.py path('technology//', views.technology, name='technology'), what is wrong in this code.. I am getting error technology() missing 1 required positional argument: 'id' -
Django add some weird characters at the end of the file
I have probelem when I submit the file to the django server and the name of the file exist in a directory. Django do not override the file, but it add some characters to the end of the name. How can I add characters instead of Django. My model.py looks like this class UpLoadFile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField() uploaded_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.file.name + ' (' + self.user.username + ')' views.py looks like this: @login_required def home(request): if request.method == 'POST': if 'upload_file' in request.POST: form = UploadFileForm(request.POST, request.FILES) form.instance.user = request.user if form.is_valid(): messages.success(request, 'Datoteka {} je bila uspešno dodana'.format(str(request.FILES["file"]))) form.save() return HttpResponseRedirect('/') else: messages.error(request, 'Datoteke {} ni bilo mogoče dodati. Preveriti če datoteka vsebuje podatke.' .format(str(request.FILES["file"]))) return HttpResponseRedirect('/') elif request.method == 'GET': upload_file = UploadFileForm() return render(request, 'update_file/home.html', {'page_title': 'Home', 'upload_form': upload_file}) forms.py looks like this: class UploadFileForm(forms.ModelForm): file = forms.FileField(required=True) class Meta: model = UpLoadFile fields = ('file',) -
django template pass argument from nav-tab (onclick) to div of another nav-pill to access it as key in dictionary
In my django application, I have a nested python dictionary as follows: JSON = { "Gadgets": { "category1": [ "key1": "value1", "key2": "value2", "key3": "value3", ] "category2": [ "key1": "value1", "key2": "value2", "key3": "value3", ] "category3": [ "key1": "value1", "key2": "value2", "key3": "value3", ] "Vehicles": { "category1": [ "key1": "value1", "key2": "value2", "key3": "value3", ] "category2": [ "key1": "value1", "key2": "value2", "key3": "value3", ] "category3": [ "key1": "value1", "key2": "value2", "key3": "value3", ] "Seasons": { "category1": [ "key1": "value1", "key2": "value2", "key3": "value3", ] "category2": [ "key1": "value1", "key2": "value2", "key3": "value3", ] "category3": [ "key1": "value1", "key2": "value2", "key3": "value3", ] .... } } In my views.py, I am passing this entire dictionary 'dict_data' to my template which is structured as shown below: The top keys - Gadgets, Vehicles, Seasons form the nav-tabs in the template; on clicking it, by default the 'LIST' nav-pill should be active and it's div should appear. However, I am unable to write a correct JS for the click function of the top nav-tabs. <!--nav-tabs click not working to make the nav-pill active--> <div class="content-object"> <ul class="nav nav-tabs nav-fill" role="tablist" id="object_tab"> {% for object in object_list %} <li class="nav-item"> <a href="#{{object}}" class="nav-link" data-toggle="tab" role="tab" … -
django template fetch ID or Name for selected dropdown value
I am building a new order form and there are few dropdowns on my HTML page. I would like to build a number based on the dropdown selection. Below is the select tag code which displays the values from the database. <div class="col-md-4 mb-5"> <select class="selectpicker show-tick" data-width="fit" id="test" data-header="Choose Cost Type Description" title="Choose Cost Type Description"> {% for row in odrrows %} <option name="costtypedesc" value = "{{ row.odr_cost}}">{{ row.odr_cost_desc}}</option> {% endfor %} <select> </div> Is there a way fetch row.odr_cost value instead of row.odr_cost_desc that too without submit? I know we can fetch the row.odr_cost_desc value using javascript but not sure about row.odr_cost. If the requirement is unclear, I can post an example. -
How to add reply and forward mail functionality in Django?
I am creating a mailing system manually(without using any third-party application). Just having a basic query about how to put reply and forward mail functionality in my mailing system. This is the model I have created: from ckeditor_uploader.fields import RichTextUploadingField class Message(models.Model): sender = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="sender") reciever = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="receiver") subject = models.CharField(max_length=100,null=True) msg_content = RichTextUploadingField(blank=True, null=True,config_name='special') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.msg_content Any idea anyone how to perform this? Thank you -
How to call a method from different admin interfaces in django?
I'm making my way trough a django (v1.10.5) project. I have two apps, each one with its own admin.py, simplified code follows: app1 -> models.py: class App1Model(models.model): pass app1 -> admin.py: class App1Admin(admin.modelAdmin): def dummyOut(self): print >> "Some output from app1" admin.site.register(App1Model, App1Admin) app2 -> admin.py: class App2Admin(admin.modelAdmin): def printFromApp1(self): #Here's where I want to access an instance of App1Admin to call dummyOut() App1Admin.dummyOut() #? which is the right way of doing that call? -
Issues with social login with vuejs and django-rest-auth
I'm working with APIs for the first time and was looking at how to set up social app authentication for the project. I have django-rest-auth set up for the backend that basically uses the django allauth framework. So when I pass an access token to the backend using the API view, it works. Now that I have moved to vuejs for the front end, I am absolutely clueless on how to make it work with my api. Any help would be greatly appreciated. I'm a total beginner for vuejs and have been working on django framework for a bit more than a month. Thanks in advance! my url settings in vuejs based on a tutorial The error I get -
Django Celery Development Worker
In production I have multiple VMs running Django + Celery I am developing new Celery Tasks on Django, Whenever I want to test if they are working, I see in Flower that the assigned worker for the task is the production VMs, even though they do not yet have the tasks and the associated code. How should I config my development server and/or rabbitMQ server to assign the development server as the worker for the development tasks? -
How to dynamically swap default model manager in django?
I am creating a project in django and django rest framework. Its and api for an angular app. The database setup consists of multiple databases. one is default database, all the django tables reside in this database; rest of the databases belong to a type of a user, each user is supposed to have a separate database. So, all the user related data goes to its separate database. To implement the selecting database dynamically, user object has an extra field to store the database to write to. from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): """Custom User model.""" database= models.CharField(max_length=9) Reason for doing this was performance improvement as each database is separate, ListView and DetailView would work faster than if the data was stored in the one database only. I know I can choose a database to store by using the using method on the model manager. In the rest api things work fine and data is being stored in their separate databases, but I end up overriding methods that django has defined. Its adding development cost to the project. Foreign keys and ManytoMany keys needs to be resolved with the current database of the user, which is not happening as I … -
getting data from two different Models at the same time
I'm working on a website that has both books and audiobooks, and there's a section on the website where I want to add the highest rated 10, which means it doesn't matter if it's a book or an audiobook I want to display the overall top 10. the way I can think I can do it is to get 5 from each and chain them with itertools, but I'm sure there's a better way. -
Page reload via ajax
Is it a proper approach to reload the page? Or how to do better? Thanks in advance) My view: def logout(request): auth.logout(request) html = render(request, 'base.html') return html Ajax: $('a[href$="logout/"]').click(function () { $.ajax({ url: '{% url "logout" %}', type: 'GET', success: function (data) { $('body').html(data); } }); return false }); -
Django - No Reverse Match Error - URL only works with static values
I'm working on a Django site that displays a list of projects. You go to a page, you see a project, you click it, and you can then see project details and have the option to edit the page. For each individual project, I use a template called project.html. Then on that page, I have a link to edit_project.html <a href="{% url 'profile:edit_project' project.id %}">Edit Project</a> Whenever I try to load the project page to view, I get this error: Reverse for 'edit_project' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_project/(?P\d+)/$'] I checked the urls, and they seemed fine. So, I tried hard-coding a project id that I knew was in the database. For example, I called: <a href="{% url 'profile:edit_project' 5%}">Edit Project</a> instead of calling that same thing with "project.id". When I did that, the error went away. Why does this work with a hard-coded value instead of a project.id variable? I also tried deleting the database and all the migrations in case something strange was happening there. I got the same issue though. Here is the code I used to set everything up in case it is helpful. project.html {% extends "profile/base.html" %} {% block content %} … -
How to display table generated with python using javascript
I am working on a django application. In this application a csv file can be uploaded using a form. Once the file is uploaded the csv file is displayed as a html table. I am using ajax so that the page does not reload when the form is submitted. The problem is I do not know how to the call the table, which is generated using pandas in the views file through javascript. this is my code so far views.py def on_csv_upload(request): path = './csv/' if request.method == 'POST': if 'file' in request.FILES: handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) df = pd.read_csv(os.path.join(path, str(request.FILES['file']))) table_heading = list(df.columns.values) table_content = df.to_html(classes='table table-bordered table-hover thead-dark', index=False) context = {'table_heading': table_heading, 'table_content': table_content} return render(request, 'index.html', context) index.html <form action="{% url 'csv_upload' %}" method="POST" enctype="multipart/form-data" class="mt-2 mb-2 csv_upload_form"> {% csrf_token %} <input type="file" name="file" id="file" class="inputfile"/> <label for="file" class="btn btn-outline-dark btn-lg btn-block select">Choose .csv file</label> <input class='btn btn-warning btn-lg btn-block upload_csv_button' type="submit" value="Upload file" disabled/> </form> index.js $(document).on('submit', '.csv_upload_form', function(event) { event.preventDefault(); csvUploadAjax(); }); function csvUploadAjax() { let $form = $(".csv_upload_form"); let form_data = new FormData($form[0]); $.ajax({ url: $form.attr('action'), type: $form.attr('method'), data: form_data, dataType: 'html', processData: false, contentType: false, success: function (data) { displayTable(data); }, error: function (xhr, … -
Django two databases (e.g. master-slave) setup results in duplicate queries
I have two databases - one is primary, the second one is replica. To read from the replica I explicitly set using statement. E.g. Object.objects.using('replica').filter(...) Also, I use select_related statement to optimise my queries. E.g. Object.objects.using('replica').select_related('item', 'item__deepitem', 'item__deepitem__deepdeepitem').filter(...) However this results in duplicate queries to master and slave dbs. I can tell this from django logs: [INFO] module: "abstract_repository" message: "Using slave 'default_slave_1' for 'Partner' queries..." [DEBUG] module: "utils" message: "(0.045) SELECT @@SQL_AUTO_IS_NULL; args=None" [DEBUG] module: "utils" message: "(0.045) SELECT @@SQL_AUTO_IS_NULL; args=None" [DEBUG] module: "utils" message: "(0.045) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None" [DEBUG] module: "utils" message: "(0.045) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None" [DEBUG] module: "utils" message: "(0.045) SELECT VERSION(); args=None" [DEBUG] module: "utils" message: "(0.045) SELECT VERSION(); args=None" [DEBUG] module: "utils" message: "(0.044) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None" [DEBUG] module: "utils" message: "(0.044) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None" [DEBUG] module: "utils" message: "(0.045) SELECT `partner`.`id` ... [DEBUG] module: "utils" message: "(0.045) SELECT `partner`.`id` ... [INFO] module: "abstract_repository" message: "Using slave 'default_slave_1' for 'Client' queries..." [DEBUG] module: "utils" message: "(0.045) SELECT `client`.`id`, ... [DEBUG] module: "utils" message: "(0.045) SELECT `client`.`id`, ... [INFO] module: "abstract_repository" message: "Using slave 'default_slave_1' for … -
DRF (Django) hierarchy structure
I need to create a hierarchy, and I added list of models, like that: class Category(models.Model): name = models.CharField(max_length=255) class Form(models.Model): parent = models.ForeignKey('Category', related_name='category', on_delete=models.CASCADE) name = models.CharField(max_length=255) class Type(models.Model): parent = models.ForeignKey('Form', related_name='form', on_delete=models.CASCADE) name = models.CharField(max_length=255) class Point(models.Model): parent = models.ForeignKey('Point', related_name='point', on_delete=models.CASCADE) name = models.CharField(max_length=255) So, please, advise how to handle this structure. I have to implement 2 cases: I need to get a record from 'point' table and it should return it with all upper hierarchy: Point-Type-Form-Category And I need to get all records from Category with full hierarchy(internal structure, which is under each record) too. So, what is the best way or instruments to implement it?