Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: filter database for current user
On my webpage I would like the user to filter the database by month and year. To do so, I created a filters.py . My problem: I did not manage the user to only filter its own data, but he is also able to see the data from the other users. So far I have tried to use @login_required and the objects.filter(user=self.request.user) method. Both didn't solve my problem. I would be grateful for any tipps! Here my code: models.py: from django.db import models from django.contrib.auth.models import User class UserDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="new_spending", null=True) expense_name = models.CharField(max_length=255) cost = models.FloatField() date_added = models.DateTimeField() filters.py from .models import UserDetails import django_filters class BudgetFilter(django_filters.FilterSet): year_added = django_filters.NumberFilter(field_name='date_added', lookup_expr='year', label='Year [yyyy]')# lookup_expr='year', month_added = django_filters.NumberFilter(field_name='date_added', lookup_expr='month', label='Month [mm]') class Meta: model = UserDetails fields = ['year_added', 'month_added'] views.py from django.shortcuts import render from .models import UserDetails from .filters import BudgetFilter from django.contrib.auth.decorators import login_required @login_required def search(request): lista = UserDetails.objects.filter(user= request.user) filtered_list = BudgetFilter(request.GET, queryset=lista) return render(request, 'budget_app/user_list.html', { 'filter': filtered_list, 'users': lista }) urls.py: from django.urls import path from . import views from django_filters.views import FilterView from .filters import BudgetFilter urlpatterns = [ ... path('search/', FilterView.as_view(filterset_class=BudgetFilter, template_name='budget_app/user_list.html'), name='search'), ] html file: … -
Django 2.2: How can I Modify a Specific Page in the Django Admin?
I am having some real trouble finding a definitive, descriptive answer to my question. Situation I need to add a URL/Link to a specific page in my Django Admin. Where I am I have modified the admin page before, but very slightly... I added a banner to my admin site to show me whether I am in a production environment or development environment like this: I did that by doing this: # templates/admin/base_site.html {% extends "admin/base_site.html" %} {% block extrastyle %} <style type="text/css"> body:before { display: block; line-height: 35px; text-align: center; font-weight: bold; text-transform: uppercase; color: white; content: "{{ ENVIRONMENT_NAME }}"; background-color: {{ ENVIRONMENT_COLOR }}; } </style> {% endblock %} - # project/context_processor.py from django.conf import settings def from_settings(request): return { 'ENVIRONMENT_NAME': settings.ENVIRONMENT_NAME, 'ENVIRONMENT_COLOR': settings.ENVIRONMENT_COLOR, } - # settings/base.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', 'wabiclean.context_processors.from_settings', ], }, }, ] Why I am stuck / Where I need help I can't quite figure out how to modify a specific page in the Django Admin. Once I figure out how to modify that specific page, I then need to modify a specific div on that page to insert … -
Django: No such file or directory found
so I am in development for a Django website. I feel like this is such a simple fix but for the life of me I can't find a solution. I know where the error is stemming from; on my index.html I am trying to show cover images for each blog post. When I remove the line where I call the object's image from the view the site runs. But when it is there I get this error: I have my file structure as follows: project/media/images (the image error.jpg is in the images folder. Here is my settings.py as I feel like this is where the problem is stemming from (at least the section I think the error is coming from. Any help at all is greatly appreciated, thanks! -
Multiple class-based views on 1 page
How can I display multiple class-based views on 1 page? For example if I want make To Do List, how do I need to implement them? -
Django ORM Retrieve Database Objects with At least 3 Matching Attributes
I have a Django application where I have a simple Pizza object with a foreign-key field set to another Object, Topping. Each Pizza has 5 toppings. I want to select a Pizza and have query the database with the ORM to retrieve any other pizzas which have at least 3 matching toppings to the Pizza selected. How do I implement the query part of this with the ORM? -
django Site matching query does not exist error
i installed allauth app , and once i try to go to my admin panel this error shows : DoesNotExist at /admin/login/ Site matching query does not exist. i know that it's configuration probleme here my settings.py file : """ Django settings for empliya project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/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__))) TEMPLATE_DIR=os.path.join(BASE_DIR,'templates') # 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 = '^%$6rgi5agbty+pa)pzt9ip$f(ffnrx)y4c1)-+orvywdznw%o' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles','accounts','search','gigpost','allauth','allauth.account','allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.linkedin', 'allauth.socialaccount.providers.twitter', ] 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 = 'empliya.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_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', ], }, }, ] WSGI_APPLICATION = 'empliya.wsgi.application' AUTH_USER_MODEL = 'accounts.User' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
How to prevent loading my Keras model at every time that I call the views in Django?
I am trying to use mobilenet in a Django app to classify images. I have already trained my model using Keras with Tensorflow backend and it is working properly without using Django. First I tried to use my model inside the view functions and it worked without any errors. However, the model is loaded every time I call this view and it takes a lot of times to reload. then I tried to define the model as a global model to load the weights only once. I have tried to initialize the model weights in the settings or in the app.py file but many problems were shown up. actually I tried to use the model without loading the weights and it worked but after loading the weight it gives me this error: this is my code: global model model = MobileNet(weights=None) model.load_weights(path) model._make_predict_function() with graph.as_default(): model.predict(img) and this is the error RuntimeError at /classifier/ Attempting to capture an EagerTensor without building a function. and this is the error before adding model._make_predict_function(): Error while reading resource variable conv_pw_12/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/conv_pw_12/kernel) … -
List One to Many Relationship
I'm sure this is a very basic question but I have a OneToMany Relationship and I wish to list all the associated children on a page. Here's what i have so far. Model File from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse ('blog-post' , kwargs = {'pk': self.pk}) class Paragraph(models.Model): content = models.TextField(default='') post = models.ForeignKey(Post,default='', on_delete=models.CASCADE) def __str__(self): return self.content class Subtitle(models.Model): subtitle = models.CharField(max_length=100,default='') post = models.ForeignKey(Post,default='', on_delete=models.CASCADE) def __str__(self): return self.subtitle View model = Post template_name = 'blog/post.html' context_object_name = 'post' HTML FILE {%block content%} {% if post.author == user %} <a href="{%url 'blog-update' post.id %}">Edit</a> <a href="{%url 'blog-delete' post.id %}">Delete</a> {% endif %} <div class = 'content'> <h2>{{post.title}}</h2> <!-- I want to show Subtitle here--><p></p> <!-- I want to show Paragraph here--><p></p> <h3>By: {{post.author}} on {{post.date_posted}}</h3> </div> {% endblock content %} -
Nginx 502 Bad Gateway with uwsgi+Django app
I am trying to set up nginx to serve my django application with uwsgi, but I am running into an error: whenever I connect to port 80, I get the nginx start page. But when I try to connect on port 8000, I get a 502 bad gateway. I am following a guide, and I am stuck at this step: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html#if-that-doesn-t-work. I've also tried following a few other guides, but I wasn't able to get it working with any of them, so maybe there's an issue with my configuration. I tried running uwsgi with the following command: uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=666 as the guide suggests, but I am still getting a permission denied error: 2020/02/23 20:26:43 [crit] 3745#3745: *25 connect() to unix:///home/bitnami/nate_site/nate_site.sock failed (13: Permission denied) while connecting to upstream, client: xxx.xxx.xxx.xxx, server: xxx.xxx.xxx.xxx, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:///home/bitnami/nate_site/nate_site.sock:", host: "xxx.xxx.xxx.xxx:8000" 2020/02/23 20:26:44 [crit] 3745#3745: *25 connect() to unix:///home/bitnami/nate_site/nate_site.sock failed (13: Permission denied) while connecting to upstream, client: xxx.xxx.xxx.xxx, server: xxx.xxx.xxx.xxx, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:///home/bitnami/nate_site/nate_site.sock:", host: "xxx.xxx.xxx.xxx:8000" systemctl status nginx shows the service running just fine, so I'm not sure why this error is appearing. I am stopping and starting these processes (nginx, django, etc.) … -
How you implement yowsup with django?
Is there anyone who integrate yowsup with Django? -
Error trying running splinter with django web browser client
I am trying to use splinter with django web browser client to have a fully python testing chain (with the possibility of java script testing). But I have this error : AttributeError: module 'django.conf.global_settings' has no attribute 'ROOT_URLCONF' I saw I can set ROOT_URLCONF into setting.configure where I already added the default charset. But I have no idea of which module I need to set in ROOT_URLCONF. Can you please give me help, or give me the smallest code to run splinter with the django web browser client. Here is my code : from splinter import Browser from django.conf import settings settings.configure(DEFAULT_CHARSE='utf-8') from splinter import Browser browser = Browser('django') url = "http://www.google.com" browser.visit(url) Thanks a lot ! -
Django-mysqlclient version error in production app uploaded on google app engine?
I have encountered this error about mysql version- django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. (Error copied from error logs in gcloud)I also encountered this same error locally so I applied this solution where I changed the base.py and operations.py files locally on my PC and it worked- Django - installing mysqlclient error: mysqlclient 1.3.13 or newer is required; you have 0.9.3 But now I am facing the same issue after deploying the webapp on Google Cloud. Any suggestions on how I can edit the same set of files specified in the other solution on gcloud? Or any other solutions? -
checking radio button on Django view from template
I am creating a custom sign up form and this is the view I created: def signup(request): if request.user.is_authenticated: return render(request, 'listings/index.html', {}) if request.method == 'POST': if 'cr-1' in request.POST: newuser = User.objects.create_user(username=request.POST.get('email'), email=request.POST.get('email'), password=request.POST.get('password')) newpatient = Patient.objects.create(user=newuser) user = authenticate(request, username=username, password=password) if user is not None: auth_login(request, user) return redirect('dashboard') elif 'cr-2' in request.POST: newuser = User.objects.create_user(username=request.POST.get('email'), email=request.POST.get('email'), password=request.POST.get('password')) newdoctor = Doctor.objects.create(user=newuser) user = authenticate(request, username=username, password=password) if user is not None: auth_login(request, user) return redirect('dashboard') else: print("##################### NOTHING HAPPENED #####################") return render(request, 'dashboard/signup.html', {}) I purposely added an else statement printing NOTHING HAPPENED on the console because nothing happens when I click on submit. Here is the template: <form class="form-type-material" method="POST" action="{% url 'signup' %}"> {% csrf_token %} <div class="custom-control custom-radio"> <input type="radio" id="cr-1" name="rg-1" class="custom-control-input" checked> <label class="custom-control-label" for="cr-1">Patient/Visiteur</label> </div> <div class="custom-control custom-radio"> <input type="radio" id="cr-2" name="rg-1" class="custom-control-input"> <label class="custom-control-label" for="cr-2">Médecin/Praticien</label> </div> <div class="form-group"> <input type="text" class="form-control" id="id_email" name="email" required> <label for="email">Adresse email</label> </div> <div class="form-group"> <input type="password" class="form-control" id="id_password" name="password" required> <label for="password">Mot de passe</label> </div> <div class="form-group"> <input type="password" class="form-control" id="id_password-conf" name="password-conf" required> <label for="password-conf">Confirmation du mot de passe</label> </div> <div class="form-group"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" required> <label class="custom-control-label">I agree to … -
Don't update dependencies while updating django app to heroku
I have deployed my django app to heroku. Now I will have to make some minor changes to the app. My understanding is that there's no way to update only one file on heroku, you have to push the whole app again. This is very time consuming. In particular the longest part is when heroku starts to reinstall all the dependencies from requirements.txt. So my question is, how do I stop heroku from reinstalling the dependencies? I heard of .gitignore. What do I need to specify there? -
TypeError at /create/
I want to create a system. For this system I need to a patient create form. When I click the button, I can save the patient but there is a error page after I pushed it. TypeError at /create/ get_absolute_url() missing 1 required positional argument: 'self' Where is my mistakes? Thanks a lot. views.py def patient_create(request): if not request.user.is_authenticated: return render(request, "http404.html") form = PatientForm(request.POST or None, request.FILES or None) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() messages.Info(request, "Success!!") return HttpResponseRedirect(newPatients.get_absolute_url()) context = { 'form': form } return render(request, "patient_form.html", context) models.py class newPatients(models.Model): title = models.CharField(max_length=100) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) created_date = models.DateTimeField(default=timezone.now) dept = models.TextField() address = models.TextField() phone = models.CharField(max_length=15) notes = RichTextField(verbose_name="notes") slug = models.SlugField(max_length=100,unique=True, editable=False) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_create_url(self): return reverse('post:create', kwargs={'slug': self.slug}) def get_unique_slug(self): slug = slugify(self.title.replace('ı', 'i')) unique_slug = slug counter = 1 while newPatients.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def get_absolute_url(self): return reverse('post:create', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = self.get_unique_slug() return super(newPatients, self).save(*args, **kwargs) class Meta: ordering = ['-created_date'] traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/create/ Django Version: 2.2.9 Python Version: 3.7.0 Installed … -
Get last instance object per each month and sum per month in Django
I tryed to search for answer but nothing yet can help me. I have one class model Activity and a class model Status : class Status(models.Model): activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name="all_status") status_date = models.DateField() actual_progress = models.DecimalField(max_digits=3, decimal_places=2) I need to get last 'status_date' for each activity for each month and sum up its actual_progress. Can't find after many research a way out. -
i have problem related to background image in css django
my background image is not shown in website the image in static folder under /projectname/static/img and css under /projectname/static/css/style.css . in css image url on #showcase { background: url("../img/showcase.jpg") no-repeat top center fixed/cover; -- other lines under it-- etc.} NOW in template under /projectname/template/pagesapp/index.html here id of section id= showcase where i want to apply image. but not shown after spend 6 days on it big problem i try this on simple project its workings but not on this. i check every thing collect static and collect static under projectanme/rentalrooms/static,settings.py where. and static root on base (projectname/static)help me plzz` #showcase { background: url("../img/showcase.jpg") no-repeat top center fixed/cover; position: relative; min-height: 650px; color: #fff; padding-top: 6rem; } #showcase .home-search { min-height: 400px; position: relative; border-radius: 5px; } #showcase .overlay { content: ''; position: absolute; top: 0; left: 0; min-height: 400px; width: 100%; background: rgba(51, 51, 51, 0.8); } {% extends 'base.html' %} {% block title %} | Welcome {% endblock%} {% load humanize %} {% block content %} <!-- Showcase --> <section id="showcase"> <div class="container text-center"> <div class="home-search p-5"> <div class="overlay p-5"> <h1 class="display-4 mb-4"> Rooms Searching Just Got So Easy </h1> <p class="lead">Stop Finding Rooms Manually Its Our Duty To … -
Dockerized Django Nginx and Postgres Issue with Nginx.conf: refused to connect
Setting up a docker-compose Django app with Nginx and Postgres is seperate dockers on a digitalocean droplet. I'm having an issue pushing to production, there is a lack of communication between gunicorn and nginx, I believe. url is printrender.com ' Here is the log from docker on my digitalocean droplet: # docker-compose -f docker-compose.yml up /usr/local/lib/python2.7/dist-packages/requests/__init__.py:83: RequestsDependencyWarning: Old version of cryptography ([1, 2, 3]) may cause slowdown. warnings.warn(warning, RequestsDependencyWarning) Starting mysite_postgres_1 Recreating mysite_django_1 Recreating mysite_nginx_1 Attaching to mysite_postgres_1, mysite_django_1, mysite_nginx_1 postgres_1 | LOG: database system was shut down at 2020-02-23 19:13:29 UTC postgres_1 | LOG: MultiXact member wraparound protections are now enabled postgres_1 | LOG: database system is ready to accept connections postgres_1 | LOG: autovacuum launcher started django_1 | mkdir: cannot create directory ‘./logs/’: File exists django_1 | ==> ./logs/gunicorn-access.log <== django_1 | django_1 | ==> ./logs/gunicorn.log <== django_1 | [2020-02-23 19:14:07 +0000] [1] [INFO] Starting gunicorn 19.9.0 django_1 | [2020-02-23 19:14:07 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) django_1 | [2020-02-23 19:14:07 +0000] [1] [INFO] Using worker: sync django_1 | [2020-02-23 19:14:07 +0000] [12] [INFO] Booting worker with pid: 12 django_1 | [2020-02-23 19:14:07 +0000] [13] [INFO] Booting worker with pid: 13 django_1 | [2020-02-23 19:14:07 +0000] [14] … -
i've never seen this error before in django-admin
hi everyone my problem is : when i try to go to my admin panel this error shows up , ps: i made a registration system for costum user AttributeError at /admin/login/ 'ellipsis' object has no attribute 'rsplit' what does this mean ? views.py: from django.shortcuts import render from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import authenticate,login,logout from django.views.generic import FormView,TemplateView,ListView from django.conf import settings from .forms import RegisterForm from .models import User # Create your views here. #user-login view def register(request): registred=False if request.method=="POST": user_register=RegisterForm(data=request.POST) if user_register.is_valid(): username=user_register.cleaned_data.get('username') email=user_register.cleaned_data.get('email') password=request.POST.get('password') user=User.objects.create(username=username,email=email,password=password) user.set_password(user.password) user.save() registred=True return HttpResponseRedirect(reverse('')) else: return HttpResponse('there is a problem') else: return render(request,'register.html',{'registred':registred,'user_register':RegisterForm}) def user_login(request): if request.method=='POST': email=request.POST.get('email') password=request.POST.get('password') user=authenticate(email=email,password=password) if user is not None: return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account not found") else: return render(request,'login.html') #user-logout view @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) thanks in advance for helping me guys azertyyuiioozzrarzereztoperiypoteiporiyeryertyr -
Write a script file (.bat or .cmd) for Windows, so I can autorun an existing Django Project on any Windows 10 PC with Python preinstalled
I already finished a Django project (development mode) and I just want to run it from any Windows PC with Python pre-installed. My project folder already includes a venv folder that was created when I create a virtual enviroment in PyCharm. I create a simple .cmd file and include this commands. venv\Scripts\activate python manage.py runserver I put this file inside the project file on the same level with manage.py file and venv folder. I don't know why but problem is that command prompt open and close without any error. I tried to run as administrator but nothing changes. When I manually open the command prompt, change the directory to the project file and run the above commands (enable virtual enviroment and runserver) everything works perfectly fine. In addition when I add this line on the top cd D:\PycharmProjects\MyProject which is the directory of my Project, nothing happens. I don't want any solution that includes installing anything more than Python (Git for Windows or such), I prefer to write a script file to successfully run python manage.py runserver with success with something that is already preistalled by default with Windows (Command Prompt or PowerShell) Thanks. -
How I display category list on my django blog sidebar?
I'm working on a Django blog I try to use django-categories pip and after setting it up successfully I'm able to categorize my post in different categories but the I'm not getting over is how I display all available categories of my blog in a list. I tried using {{ category.name }} but nothing is displayed in blog sidebar. -
Django FieldError at /create/
I want to create a patient form for my system. I entry all values but it cannot save the patient and shows an error. Where is my mistake? FieldError at /create/ Cannot resolve keyword 'slug' into field. Choices are: address, created_date, dept, first_name, id, last_name, notes, phone, title Thanks for your attention. Traceback: File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\edeni\senior\pharsys\patients\views.py" in patient_create 29. post.save() File "C:\Users\edeni\senior\pharsys\patients\models.py" in save 39. self.slug = self.get_unique_slug() File "C:\Users\edeni\senior\pharsys\patients\models.py" in get_unique_slug 33. while newPatients.objects.filter(slug=unique_slug).exists(): File "C:\Users\edeni\senior\myenv\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\db\models\query.py" in filter 892. return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 910. clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\db\models\sql\query.py" in add_q 1290. clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\db\models\sql\query.py" in _add_q 1318. split_subq=split_subq, simple_col=simple_col, File "C:\Users\edeni\senior\myenv\lib\site-packages\django\db\models\sql\query.py" in build_filter 1190. lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\db\models\sql\query.py" in solve_lookup_type 1049. _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\db\models\sql\query.py" in names_to_path 1420. "Choices are: %s" % (name, ", ".join(available))) Exception Type: FieldError at /create/ Exception Value: Cannot resolve keyword 'slug' into field. Choices are: address, created_date, dept, first_name, id, last_name, notes, phone, … -
How to solve "django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty" when using a service method in a venv?
I'm using Django 2.0 and Python 3.7. I have this settings file, articleagg_project/settings/base.py, with this defined ... # This is the default header sent to the scraping requests HDR = {'User-Agent' : 'super happy flair bot' } When I try and run a service method I have defined in my virtual environment, it seems to have trouble accessing the above setting ... localhost:articleagg_project davea$ source venv/bin/activate (venv) localhost:articleagg_project davea$ python ... >>> from articleagg.services.media_service import MediaService >>> code = MediaService.doImageSearch(image_url) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/davea/Documents/workspace/articleagg_project/articleagg/services/media_service.py", line 79, in doImageSearch headers = settings.HDR File "/Users/davea/Documents/workspace/articleagg_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/Users/davea/Documents/workspace/articleagg_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/Users/davea/Documents/workspace/articleagg_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 126, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. The offneding line 79 where this is dying looks like this headers = settings.HDR I import my settings earlier in my service file like so ... from django.conf import settings So what else do I need to do to get this to run in my virtual environment? -
Is there a way to make @import work in CSS files within Django?
The CSS stylesheets in my Django website are served as static files (so their URLs are constructed using the {% static %} template tag), but I find myself in need of importing a CSS file inside another CSS file, where Django template tags will not work. Is there a way to dynamically populate the argument to @import inside a CSS file? Or will I have to just <link> the two files separately inside the HTML page? -
select checkbox and display pats of form accordingly
have the code for two checkboxes but how can I do it for 3?