Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: sort the table data according alphabetically
What I have is: models.py: class Address(custom_mixins.SiteAwareAbstractModel): states = State.objects.all() CHOICES = list() for state in states: CHOICES.append((state.code, state.name)) CHOICES = tuple(CHOICES) state_name = models.CharField(max_length=80, choices=CHOICES) Then the State class class State(models.Model): name = models.CharField(max_length=256) code = models.CharField(max_length=2, null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-id'] def __str__(self): return '{}'.format(self.name) This renders all the states as they're stored in the table. What I want is to display all the states in the alphabetically order. I tried doing: states = State.objects.all().order_by( 'name').values_list( 'code', flat=True) But this threw the error CHOICES.append((state.code, state.name)) AttributeError: 'str' object has no attribute 'code' -
issue while creating a different database inside django application while deployed in docker
I am working in django framework docker environment and i have a script which builds a database if not created. Facing issue is that while trying to deploy the image the script is creating a database but i am facing an issue. sqlite3.OperationalError: unable to open database file Can anyone helpme? -
Countdown timer resets after page refresh django
I'm trying to set up a countdown timer in seconds for a website in construction which works perfectly, but I'm failing to wrap my head around how to set up a function for current date and end date, so that the timer doesn't reset every time i load the site. I've tried var compareDate = new Date(yyyy,MM,dd,hh,mm,ss);, I've also tried setting up cookies and saved settings but neither seems to work for me. Are there any other workarounds? This is my current function: (function($) { $.fn.ClassyCountdown = function(options, callback) { var element = $(this); var DaysLeft, HoursLeft, MinutesLeft, SecondsLeft; var secondsLeft; var isFired = false; var settings = { end: undefined, now: $.now(), labels: true, labelsOptions: { lang: { days: 'Days', hours: 'Hours', minutes: 'Minutes', seconds: 'Seconds' }, style: 'font-size: 24px;' }, css: .ClassyCountdown-wrapper > div { display: inline-block; position: relative; width: calc(15% - 10px); margin: 10px; left:290px; } .ClassyCountdown-wrapper .ClassyCountdown-value { width: 100%; line-height: 1em; position: absolute; top: 50%; text-align: center; left: 0; display: block; } html: <div class="display-table center-text"> <div class="display-table-cell"> <div id="rounded-countdown"> <div class="countdown" data-remaining-sec="3999600"></div> </div> </div><!-- display-table-cell --> </div><!-- display-table --> I understand that this is noob question but please have sympathy for me brethren i've … -
A Django form doesn't show up
I am trying to create a simple login form using Django and Bootstrap. I used a tutorial about combining Bootstrap and Django, but it doesn't work. I reviewed my code a few times and checked another topics and didn't managed to find a solution. I So, here is my views.py: from django.shortcuts import render from .forms import login_form # Create your views here. from django.http import * def index(request): if request.method == "POST": name = request.POST.get("email") # age = request.POST.get("age") # getting age return HttpResponse("<h2>Hello, {0}</h2>".format(name)) else: userform = login_form() return render(request, "index.html", {"form": userform}) And index.html: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <meta charset="UTF-8"> <title>Password Generator Main Page</title> <script> $(document).ready(function(){ $("#login-form-link").click(function(){ $(".register-form").hide(); $(".login-form").show(); }); $("#register-form-link").click(function(){ $(".login-form").hide(); $(".register-form").show(); }); }); </script> </head> <body> <div class="main-block"> <div class="login-signup"> <div class="login-menu"> <br/> <p class="log-reg-link"><a href="#" id="login-form-link">Login</a></p> </div> <div class="signup-menu"> <br/> <p class="log-reg-link"> <a href="#" id="register-form-link" class="active">Sign Up</a></p> </div> </div> <div class="form-holder"> <form class="login-form" action="#" method="post" style="display: block;"> {% csrf_token %} <table> {{ login_form }} </table> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> <button type="submit" class="btn btn-lg btn-primary">Login</button> </div> </div> … -
django reportlab not producing pdf
I want to make a view were the user can download a pdf. So I've started with the basics. I've installed reportlab and used the django documentation to create my first pdf. So here is my function in views.py : #Libraries from django.shortcuts import render from django.http import HttpResponse from ExportScelles.forms import * import xlsxwriter from datetime import date, datetime, timedelta from AffichageScelles.models import * from django.db.models import Q from reportlab.pdfgen import canvas def exportPDF(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = "attachment; filename= somefilename.pdf" # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response It's exactly the same function that the one in the documentation. I've also written in the urls.py : from django.urls import path from . import views urlpatterns = [ path('export/xlsx/', views.export, name='export'), path('export/pdf/',views.export,name ='pdf'), ] I don't have any error when I compile but when I go on the adress .../export/pdf/ nothing … -
Django/Nginx - Not serving media files over approx. 3 Mb
When user uploads image, it is stored in media folder inside project directory. The problem is that when they want to see it on the website, nginx return 403 Forbidden error for images over approximately 3 Mb. I set nginx.conf client_max_body_size to 8M http { ## # Basic Settings ## client_max_body_size 8M; ... And already changed memory size in settings.py: FILE_UPLOAD_MAX_MEMORY_SIZE = 8388608 When I upload an image under 3 MB, there are no problems, if I upload image over 3 MB, I can see it inside media folder but the error is raised instead of serving image: GET https://example.com/media/images/dom.jpg 403 (Forbidden) I noticed that files under 3 MB have different permissions: -rw-r--r-- 1 django www-data 4962 Jul 19 19:51 61682_3995232_IMG_01_0000.jpg.150x84_q85_crop.jpg -rw-r--r-- 1 django www-data 1358541 Jul 20 09:32 byt.jpg -rw------- 1 django www-data 3352841 Jul 20 09:32 dom.jpg -rw-r--r-- 1 django www-data 5478 Jul 19 20:10 downloasd.jpeg.150x84_q85_crop.jpg -rw-r--r-- 1 django www-data 3225 Jul 9 22:53 images.jpeg.100x56_q85_crop.jpg -rw-r--r-- 1 django www-data 6132 Jul 19 20:00 NorthYorkHouse2.JPG.150x84_q85_crop.jpg Do you know where is the problem? -
Django Money - Add two MoneyFields in different currencies and generate output in given currency
Hi I've been scratching my head over past few days to figure out how to manipulate dj-money fields. Here are my two model fields: client_cost = MoneyField( _('client cost'), max_digits=10, decimal_places=2, default_currency='AUD', null=True, ) camera_operator_cost = MoneyField( _('camera operator cost'), max_digits=10, decimal_places=2, default_currency='AUD', null=True, ) They can have completely different currencies (default being 'AUD'). I need to be able to: extract currency from these fields. (Need the exact statement). add these two fields which could have amounts in any currency. reformat the total in whatever currency I want. Let's say total in AU$ is 250 and now i want the same value in US$ which will be ~184US$ Please help. PS: I'm using this: https://github.com/django-money/django-money -
django difference between two timestamp in django template
Suppose, I have a timestamp 2018-07-20 14:47:12.984313+06 and I need to calculate the difference with 2018-07-20 14:50:12.984313+06 in Django template. It should return 3 as result. How can I do this? -
Menu with permissions in django
I am creating a modular menu in Django that has the following structure; class Pagina(models.Model): nome = models.CharField(max_length=250, blank=True) url = models.CharField(max_length=250) def __str__(self): return self.nome class Voce(models.Model): nome = models.CharField(max_length=250, blank=True) Pagine = models.ManyToManyField(Pagina) Permesso = models.ForeignKey(Permesso, on_delete=models.CASCADE) def __str__(self): return self.nome class Menu(models.Model): Voci = models.ManyToManyField(Voce) I need to check if the user has the required permission to see the submenu(permission that is in a group). The menu is rendered the following way; {% for voce in menu.Voci.all %} <li class="m-menu__item m-menu__item--submenu m-menu__item--rel {% ifequal parent voce.nome %}m-menu__item--active{% endifequal %}" m-menu-submenu-toggle="click" aria-haspopup="true"> <a href="javascript:;" class="m-menu__link m-menu__toggle"> <span class="m-menu__item-here"></span><span class="m-menu__link-text">{{voce}}</span><i class="m-menu__hor-arrow la la-angle-down"></i><i class="m-menu__ver-arrow la la-angle-right"></i> </a> <div class="m-menu__submenu m-menu__submenu--classic m-menu__submenu--left"><span class="m-menu__arrow m-menu__arrow--adjust"></span> <ul class="m-menu__subnav"> {% for pagina in voce.Pagine.all %} <li class="m-menu__item {% ifequal request.path pagina.url %}m-menu__item--active{% endifequal %}" aria-haspopup="true"> <a href="{{pagina.url}}" class="m-menu__link "> <i class="m-menu__link-bullet m-menu__link-bullet--line"><span></span></i> <span class="m-menu__link-title"><span class="m-menu__link-wrap"><span class="m-menu__link-text">{{pagina.nome}}</span></span></span> </a> </li> {% endfor %} </ul> </div> </li> {% endfor %} The check would need to happen just after the first for loop starts in order to determine whether or not to display that particular submenu. The "gruppo" object of the user is a foreignkey relation to a personalized Group object, which has a ManyToMany relation with … -
Django not appending slash to admin URL
I'm using Django for my project's backend, and React on the frontend. As such, I have to specify a fallback URL which serves up index.html, which contains the script for all of my frontend code. However I want Django to match admin and admin/. The Regex below solves the problem, but accessing admin doesn't append a slash (I have APPEND_SLASH set to True in settings). The result is ugly looking urls like adminapis instead of admin/apis when I am using the admin interface. Any idea how I can preserve the trailing slash? urlpatterns = [ re_path(r"admin/?", admin.site.urls), path("", include("api.urls", namespace="api")), re_path(r".*", TemplateView.as_view(template_name="index.html")), ] -
Reload the page after clicking a form button in IE
I have a problem with my web site. I have a button that displays the form and the problem is that on IE and on the edge when I click this button it shows me the form but refreshed the page automatically after the click. I do not know how to solve this problem. Can you help me please ? Here is my code html : <div class="col-xs-3" id="div6"> <div style="text-align: center; color: #333; font-weight:bold;">Actualité</div> {% if user.is_authenticated %} {% if request.user.is_staff %} <form action="#modification"> <div style="text-align: center;"> <button type="submit" id="modifier" class="btn btn-primary">Modifier l'actu</button> </div> </form> <form action="#modification" id="formActu" style="display: none" method="post"> {% csrf_token %} <div id="modification"></div> <div style="text-align: center;"> <button type="submit" class="btn btn-success" id="valider" style="margin-top: 1%;">Valider</button> </div> </form> {% endif %} {% endif %} {% if not actu %} <div id="messageNonActu" style="margin-top: 5%;">Pas d'actualité pour le moment !</div> {% endif %} {% for actuCommentaire in actu %} <div id="commentaireActu" style="margin-top: 5%;">{{actuCommentaire.commentaire}}</div> {% endfor %} </div> Here is my script : $(document).ready(function(){ var compteur = 0; $('#modifier').click(function(){ if(compteur === 0){ $('#modification').append('{% for field in form %}<label class="my_class" for="{{ field.name|escapejs }}">{{ field.label|escapejs }} :</label>{{ field|escapejs }}{% endfor %}'); $('#formActu').show() $('#exampleTextarea').css({resize: 'none'}); $('#commentaireActu').hide(); $('#messageNonActu').hide(); $('#modifier').removeClass('btn btn-primary').addClass('btn btn-danger'); $('#modifier').html("Annuler la modif"); compteur++; }else{ … -
How to redirect to success after POST method in Django 2 and success message to display after redirect
I would like to know how a GET OR POST requests can be handled from a FormView class to render a unbound form for GET and POST the form to database for POST and subsequently redirect to success page (info message). What template to use for GET and POST methods and how to include message after redirect to success URL? views.py: from django.shortcuts import render,redirect,render_to_response,get_object_or_404 from django.forms import ModelForm from django.views import View from django.views.generic.edit import CreateView from .forms import MyPlaceForm from .models import Place from django.urls.base import reverse_lazy from django.contrib import messages #Ceate your class-based views here. class MapView(View): def get(self, request): 'Display map' return render(request,template_name='index.html') # Handling forms with class-based view class PlaceFormView(View): form_class = MyPlaceForm initial = {'key': 'value'} template_name = 'name.html' # Provide Blank Form if GET request def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) # Provide a message if POST request def post(self, request, *args, **kwargs): form = self.form_class(request.POST) success_url=reverse_lazy('success') if form.is_valid(): # <process form cleaned data> messages.add_message(request, messages.INFO, 'Hello world.') return reverse_lazy(success_url) return render(request, self.template_name, {'form': form}) -
how can i use inbuilt django authentication and admin panel with MongoDB ? How can i make a connection like regular SQL in settings.py for mongoDB
connection with this settings works for CRUD methods but is incompatible for admin panel and authenticaion.if there is some way by which i can make connection with MongoDB like our regular POSTGRES,SQLITE eg with engine and port numbers in DATABASE Varibale in Settings.py file . Please Suggest # Settings.py """ Django settings for calculator project. Generated by 'django-admin startproject' using Django 2.0.2. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os DBDNAME='mydata' _MONGODB_HOST='localhost' _MONGODB_NAME='mydata' _MONGODB_DATABASE_HOST = \ 'mongodb://%s:%s@%s/%s'\ %('','',_MONGODB_HOST,_MONGODB_NAME) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '3gcc++w$zhw7k=4&)po*r4_sqc_u7vhbqt0vpdsx(&-#ob#taj' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'calc.apps.CalcConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'calculator.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] … -
Django - inject context into base.html
I am trying to inject context(single_well_info) into my base.html. Base is extended by contextual_main.html views.py class ContextualMain_DetailView(DetailView): template_name = 'contextual_main.html' context_object_name = 'single_well_info' model = models.WellInfo context_processor.py from contextual.views import ContextualMain_DetailView def add_context_to_base(request): return {'single_well_info': # context instance} When ContextualMain_DetailView.as_view() is called, a model class instance single_well_info is injected into contextual_main_html I decided to create a context_processor to inject this exact same context into base.html How can I modify my context_processor.py to get the exact same model class instance single_well_info inside ContextualMain_DetailView ?? -
How to get URL Parameter in Forms for Function Based View (Django)
I am trying to get my url parameter value in my form however I am unsure of how to do so. Many answers online that I found from are only for Class Based Views. This is my path: path('courses/<str:course_abbr>/<str:module_abbr>/<int:year>/<int:semester>/<int:stage>/designations', views.designations, name='designations') This is my form which I am trying to get course_abbr into: class DesignationForm(forms.Form): class Media: css = { 'all': ('admin/css/responsive.css', 'admin/css/base.css', 'admin/css/widgets.css',) } js = ('/admin/jsi18n',) module_coordinator = forms.ModelMultipleChoiceField(queryset=Staffs.objects.all(), widget=FilteredSelectMultiple("Module Coordinator", is_stacked=False), required=False, label="") instructor = forms.ModelMultipleChoiceField(queryset=Staffs.objects.all(), widget=FilteredSelectMultiple("Instructor", is_stacked=False), required=False, label="") moderator = forms.ModelMultipleChoiceField(queryset=Staffs.objects.all(), widget=FilteredSelectMultiple("Moderator", is_stacked=False), required=False, label="") verifier = forms.ModelMultipleChoiceField(queryset=Staffs.objects.all(), widget=FilteredSelectMultiple("Verifier", is_stacked=False), required=False, label="") invigilator = forms.ModelMultipleChoiceField(queryset=Staffs.objects.all(), widget=FilteredSelectMultiple("invigilator", is_stacked=False), required=False, label="") -
Register Service Worker in Django
I am trying to register service worker in django but I get this error DOMException: Failed to register a ServiceWorker: The script resource is behind a redirect, which is disallowed. My project structure is src/ templates/sw.js static/js/main.js #file where I register service worker main.js if ('serviceWorker' in navigator) { navigator.serviceWorker .register('sw.js', {scope: '/'}) .then(function(reg) { console.log('Achieng Service worker Registration worked!'); }) .catch(function(error) { console.log(error); }); } According to this django-service worker, I have defined my urls as path('sw.js/', (TemplateView.as_view(template_name="sw.js", content_type='application/javascript', )), name='sw.js'), and have my sw.js in templates folder. What could I be missing? I want service worker to have a default scope '/' -
Django Updateview - set parameter based on field value or user object
I have a Django UpdateView with a form. In the template I have to show a 'name' value. In case there is customer_id value present in the form, then 'name' is based on that value. If it is empty, then 'name' is based on the user object. The 'name' is not saved in the model, so it has to be calculated. Seems simple, but I cannot get it to work. What I have tried this far: Try to set the value in get_context_data() - not working because get_context_data is called before the form data is bound so I cannot access the customer_id value from the form. Make a method in the form class: def get_name(self): if self.is_bound: # return name based on form.cleaned_data['customer_id'] else: # return name based on self.user.user_id Call the method in the template... but it always returns name based on user. I can see input fields in template with values, but somehow the form is not bound? I'm not really comfortable with CBV's, but I can't change it to use a FBV. Any ideas how could I accomplish this? Thanks in advance! -
Django - left joining date array with a queryset
In my Django project, I have the following model: class Examine(models.Model): name = models.CharField(max_length=45) date = models.DateField(blank=True, null=True) My goal is to come up with a queryset that would enable me to render a template with list of dates and the examines for the date - if any. For example, I have two examines in the DB: Math - 01 January 2019, History - o3 January 2019 Geoghraphy - 03 January 2019 and I am interested in the date interval January 1 to January 4 2019. THe output should be: January 1 Math January 2 No exams January 3 History Geography January 4 No exams I have two years of experience with Django ORM, but can't even submit any of my attempts of how I tried to implement this. I have no ideas. Is it possible in Django ? -
django: css in static folder shows 404 error but not js files
I am new to django, I have a working django application in the public server. Now I want to make it work in the local server. so, I downloaded all the files from the server I installed virtualenv, installed same django version as in the public server. Changed username and password for mysql database It works, but Style is not applied. I have every static files in static folder, it's in the same location as manage.py If view the source, It appears like this <script src='/static/js/jquery-3.3.1.min.js'></script> <script src='/static/js/bootstrap.min.js' async defer></script> <link href='/static/css/bootstrap.min.css' rel='stylesheet' async> If I right click and open the js files it works, but if I open css file it shows 404 error. Why is that only css is not working In settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') In the main urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Please tell me if you need to any other info, because I dont know what is very relevant for this question. -
Not able to connect mysql database with django framework
i am trying to connect mysql database with django framework but it is not getting connect. Setup: xampp installed,django installed,mysqlclient installed Created a database using phpmyadmin with the database name as polls settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'polls', 'USER': 'root', 'PASSWORD': '', 'HOST':'localhost', 'PORT':'3306' } } error when i run python manage.py migrate: Traceback (most recent call last): File "/home/akshay/.local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/akshay/.local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/akshay/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection return Database.connect(**conn_params) File "/home/akshay/.local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 85, in Connect return Connection(*args, **kwargs) File "/home/akshay/.local/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/akshay/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/akshay/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/akshay/.local/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/akshay/.local/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/akshay/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/akshay/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 57, in _run_checks issues = run_checks(tags=[Tags.database]) File "/home/akshay/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/akshay/.local/lib/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) … -
Pycharm cant install Django Rest Framework
i have been following for a tutorial for learning the Django rest framework and have been using pycharm to do it. Typically when i do pip install and install it in the package modules in the settings, the red squiggly lines go away and the package is installed. I have also tried alt+enter with the cursor over the package but not luck with that either. I have tried using conda as well but i end up getting the same result: conda install -c conda-forge djangorestframework I would normally ignore the red squiggles but i have found that since it doesnt recognize that the package is installed, i cant use it when i run the shell and try to test stuff out using rest_framework. thus it throws an error. These are the packages i have installed through pip: django-filter==2.0.0 django-rest-framework==0.1.0 djangorestframework==3.8.2 idna==2.7 Markdown==2.6.11 Pillow==5.2.0 pytz==2018.5 requests==2.19.1 urllib3==1.23 i am running pycharm version: I cant figure out why the rest_framework module cant be installed into pycharm. This is the error its giving me: Does anyone know how to resolve this or perhaps know where start? Thank you in advance! -
Django - get object instance in context_processors & inject context into base.html
I am trying to inject context(single_well_info) into my base.html. Base is extended by contextual_main.html views.py class ContextualMain_DetailView(DetailView): template_name = 'contextual_main.html' context_object_name = 'single_well_info' model = models.WellInfo When ContextualMain_DetailView.as_view() is called, a model class instance single_well_info is injected into contextual_main_html I decided to create a context_processor to inject this exact same context into base.html context_processor.py from contextual.views import ContextualMain_DetailView def add_context_to_base(request): return {'single_well_info': # context instance} How can I modify my context_processor.py to get the exact same model class instance single_well_info inside ContextualMain_DetailView ?? -
Dynamic naming of uploaded files based on a condition
I am uploading images in a Django application. This is my models.py. def file_rename(instance, filename): ext = filename.split('.')[-1] count = Count.objects.get(pk=1) ZSN = "ZT-WJ-" + str(count.jeans_count + 1) filename = '{}.{}'.format(ZSN, ext) return os.path.join('images', filename) class Images(models.Model): design_id = models.CharField(max_length=128) file = models.ImageField(upload_to=file_rename) cost_price = models.FloatField() category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=False) Here all the uploaded images are being stored with names as 'ZT-WJ-' + count_of_image. But I don't want 'ZT-WJ-' to be static. I want it to be based on the category to which the image belongs. How do I do this without interfering with the front-end and not using JavaScript? -
You do not have permission to perform this action when accessing api in django
i am trying to add custom permissions in my Django app using Django rest framework. i created an API n tested it in postman it works fine for authenticated user. however it doesnt display details when i visit details view . for example when i visit http://localhost:8000/placeslist/ it displays all the places but when i try http://localhost:8000/placeslist/1/ it says you dont have permission. i dont know where i went wrong models.py class Places(BaseModel): name = models.CharField(max_length=255,null=True,default='') owner=models.ForeignKey('auth.User',related_name='place_list',on_delete=models.CASCADE,null=True) Views.py class PlacesView(generics.ListCreateAPIView): queryset = Places.objects.all() serializer_class = PlacesSerializer permission_classes = (permissions.IsAuthenticated, IsOwner) def perform_create(self,serializer): serializer.save(owner=self.request.user) class PlacesDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Places.objects.all() serializer_class = PlacesSerializer permission_classes = (permissions.IsAuthenticated, IsOwner) Permission.py class IsOwner(BasePermission): def has_object_permission(self, request, view, obj): if isinstance(obj, Places): return obj.owner == request.user return obj.owner == request.user Serializer.py class PlacesSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Places fields =('id','name','owner') urls.py url(r'^placeslist/$', PlacesView.as_view(), name="place"), url(r'placeslist/(?P<pk>[0-9]+)/$',PlacesDetailView.as_view(), name="place_details"), url(r'^get-token/', obtain_auth_token), Settings.py .... REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', ) } .... -
Django ModuleNotFoundError: No module named 'idoc' in Apache with mod_wsgi
Getting following error when I try to run my Django project in Apache with mod_wsgi. Below is the error trace: Loading Python script file '/var/www/django/apac_o2c_idoc/idoc/wsgi.py'. [Fri Jul 20 06:34:01.437544 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] mod_wsgi (pid=3101): Failed to exec Python script file '/var/www/django/apac_o2c_idoc/idoc/wsgi.py'. [Fri Jul 20 06:34:01.437678 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] mod_wsgi (pid=3101): Exception occurred processing WSGI script '/var/www/django/apac_o2c_idoc/idoc/wsgi.py'. [Fri Jul 20 06:34:01.438950 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] Traceback (most recent call last): [Fri Jul 20 06:34:01.439067 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] File "/var/www/django/apac_o2c_idoc/idoc/wsgi.py", line 34, in <module> [Fri Jul 20 06:34:01.439081 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] application = get_wsgi_application() [Fri Jul 20 06:34:01.439093 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] File "/var/www/django/apac_o2c_idoc/venv/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Fri Jul 20 06:34:01.439098 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] django.setup(set_prefix=False) [Fri Jul 20 06:34:01.439108 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] File "/var/www/django/apac_o2c_idoc/venv/lib/python3.6/site-packages/django/__init__.py", line 19, in setup [Fri Jul 20 06:34:01.439112 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Fri Jul 20 06:34:01.439120 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] File "/var/www/django/apac_o2c_idoc/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ [Fri Jul 20 06:34:01.439143 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] self._setup(name) [Fri Jul 20 06:34:01.439152 2018] [wsgi:error] [pid 3101] [remote 17.82.221.203:61634] File "/var/www/django/apac_o2c_idoc/venv/lib/python3.6/site-packages/django/conf/__init__.py", …