Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URL Patterns issue with Path statements
I'm following a Django/Python online course which is a little dated using URL statements instead of path statements. I'm getting the following error. The code segment is below as well. Please help. Thanks so much! enter image description here enter image description here -
Django server fails to start in webbrowser
I am trying to run a Django Project, using PayCharm. Here what I get: And when I klick on the Link, I see the following: How can I resolve this Problem? -
django image not loading from media_root
i am making a products page for an ecommerce project, i have already successfully loaded the images using django admin into an image directory in the base root of my project. The challenge am currently facing is that when i try to display the product images on the shop products page it does not work. how do i make it work ? my setttings.py file looks like this: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR ,'media') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static','static_root') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_files'), ] TEMPLATE_DIRS = [ os.path.join(BASE_DIR, 'templates'), ] my urls.py file looks like this: from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from products.views import home, all_products_view urlpatterns = [ path('',home, name="home"), path('products/',all_products_view, name="all_products"), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, ducument_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, ducument_root = settings.MEDIA_ROOT) below is a code for products template where the images are supposed to be loaded {% extends "base.html" %} {% block products %} {% for product in products %} <div class="col-lg-3"> <div class="card-deck"> <div class="card p-2 mb-2"> {% for item in product.productimage_set.all %} <img src="{{ item.image.url }}'" alt=""> {% endfor %} </div> </div> </div> {% … -
Function doesn't call another function in Django views
I have a chain of functions, that i need to execute consistently like this: user_profile() -> deposit_counter() -> test() However, my test function is not executing. What is wrong with it? def user_profile(request): try: print('deposit counter') deposit_counter(request) except Profile.DoesNotExist: return render(request, "../templates/profile.html") def deposit_counter(request): deposit_object = Deposits.objects.get(id=request.user.profile.deposits.id) deposit_type_object = getattr(deposit_object, 'deposit_type') if deposit_type_object == Deposits.DEPOSIT_TYPE[0][0]: tax = 13 Deposits.objects.update(tax_rate=13) percentage = 0.11 print('i am hit') test(request, percentage, tax) def test(request, percentage, *args): deposit_object = Deposits.objects.get(id=request.user.profile.deposits.id) deposit_value_object = getattr(deposit_object, 'deposit_value') deposit_creating_date = getattr(deposit_object, 'deposit_creating_date') deposit_end_date = getattr(deposit_object, 'deposit_end_date') deposit_income = deposit_value_object * (percentage/100) * (args / 100) Deposits.objects.update(temporary_deposit_income=deposit_income, temporary_total_income=(deposit_income + deposit_value_object)) print('I am here') if deposit_creating_date == deposit_end_date: Deposits.objects.update(deposit_income=deposit_income, total_income=(deposit_income + deposit_value_object), temporary_deposit_income=None, temporary_total_income=None) Account.objects.update(current_balance=(deposit_income + deposit_value_object)) -
Django: all auth create account with email - unique constraint failed. Display message instead of giving an error
I am using djnago all-auth to create custom user accounts. When creating an account with email and password, if account with a email already exits it gives an error (UNIQUE constraint failed: account_emailaddress.email) but I would like to display message that an account with this email already exists instead of throwing an error. What is the best way to handle this? In general I would use AJAX to verify and display message for my own views but I do not know how to deal here with django all-auth package. -
PostgreSQL Function not working with WHERE clause
I am trying to make a function in postgres to make my queries faster compared to Django ORM. But the problem I am facing is results are coming when there is no WHERE clause in the query. This is the function and its call which yeilds 0 rows: CREATE OR REPLACE FUNCTION public.standard_search(search_term text, similarity_to integer) RETURNS TABLE(obj_id integer, app_num integer, app_for text, similarity integer) LANGUAGE 'plpgsql' AS $BODY$ DECLARE similarity integer; BEGIN RETURN QUERY SELECT mark.id, mark.app_num, mark.app_for::text, levenshtein($1, focusword.word) AS similarity FROM mark INNER JOIN focusword ON (mark.id = focusword.mark_id) WHERE similarity <= $2 ORDER BY similarity, mark.app_for, mark.app_num; END $BODY$; select * from public.standard_search('millennium', 4) This is the function and its call which is giving me results but is slow as the filtering is done in the function call: CREATE OR REPLACE FUNCTION public.standard_search(search_term text, similarity_to integer) RETURNS TABLE(obj_id integer, app_num integer, app_for text, similarity integer) LANGUAGE 'plpgsql' AS $BODY$ DECLARE similarity integer; BEGIN RETURN QUERY SELECT mark.id, mark.app_num, mark.app_for::text, levenshtein($1, focusword.word) AS similarity FROM mark INNER JOIN focusword ON (mark.id = focusword.trademark_id) ORDER BY similarity, trad.app_for, mark.app_num; END $BODY$; select * from public.standard_search('millennium', 4) where similarity <= 4 Can anyone shed some light on what is … -
Django/Python - How do I get a count of records in a model where an @property function is True?
I'm very new to python and django and I'm working on a version of the locallibrary project to learn some concepts. I've created a model with an @property to show when an item is overdue: @property def overdue(self): is_overdue = False if (datetime.date.today() > self.due_date) and self.status != 'c': is_overdue = True return is_overdue I would like to get a count of all items where overdue=True. In templates I can use 'overdue' as if it were a field, however, trying to use is in a view like this... num_actions_overdue = Action.objects.filter(overdue='True').count() ...throws an error: Cannot resolve keyword 'overdue' into field. Is there a simple way to count all overdue records? Thanks in advance for any help! -
How to configure django to run on apache
Been having problems for the last 3 days with this... I was able to install and run apache on CentOs machine, I can run simple html or wsgi files, my problem is when I try to run django, django project runs ok with manage.py runserver, but when configuring the wsgi.py file and the .config, I start to having problems on the website (500 error); error_log; [Mon Apr 20 09:59:59.532476 2020] [:error] [pid 31466] [client 10.5.230.111:59479] File "/srv/www/example/mysite/mysite/wsgi.py", line 14, in [Mon Apr 20 09:59:59.532591 2020] [:error] [pid 31466] [client 10.5.230.111:59479] from django.core.wsgi import get_wsgi_application [Mon Apr 20 09:59:59.532627 2020] [:error] [pid 31466] [client 10.5.230.111:59479] ImportError: No module named django.core.wsgi example.config; WSGIDaemonProcess python-home=/var/www/django/env/ python-path=/srv/www/example/mysite:/var/www/django/env/lib/python3.6/site-packages WSGIProcessGroup %{GLOBAL} WSGIScriptAlias /exam /srv/www/example/mysite/mysite/wsgi.py <Directory /srv/www/example/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> # Django static files, here you must specify your own path's Alias /static/ /srv/www/example/mysite/static/ <Directory "/srv/www/example/mysite/static"> Require all granted </Directory> wsgi; import os import sys import site for root, _, files in os.walk('/usr/local/lib/python3.4/site-packages/django'): for f in files: os.system('dos2unix %s' % abspath(join(root, f))) from django.core.wsgi import get_wsgi_application site.addsitedir("/var/www/django/env/lib/python3.6/site-packages") sys.path.append("/srv/www/example/mysite") sys.path.append("/srv/www/example/mysite/mysite") activate_this = "/var/www/django/env/bin/activate_this.py" with open(activate_this) as f: code = compile(f.read(), activate_this, "exec") exec(code, dict(file=activate_this)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() Already tried multiple things (https://www.slideshare.net/GrahamDumpleton/getting-started-with-modwsgi, … -
Django with Apache Webserver on Ubuntu Server: Trying to login with Active Directory Users
i'm trying to authenticate my django users via the ldap interface of the domain controller. My test code worked successfully to contact the active directory. But configuring django to accept this didn't work till now. My test to login with the browser at Hostname/admin did not work: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. Are my settings at settings.py correct and do I have to activate them for django (or apache)? Which username should I use for login at django login? Like in windows login? python manage.py check brings no failures. Here is my settings.py excerpt: import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType AUTH_LDAP_SERVER_URI = "ldap://<IP Adress>" AUTH_LDAP_BIND_DN = "cn=<existing_bind_user>,ou=<xxx>,dc=<domain>,dc=com" AUTH_LDAP_BIND_PASSWORD = "<password>" AUTH_LDAP_USER_DN_TEMPLATE = 'sAMAccountName=%(user)s,ou=<xxx>,dc=<domain>,dc=com' #Inside the ou "Django" are the 3 different groups G_Django_Admin,G_Django_User,... AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=Django,ou=<xxx>,dc=<domain>,dc=com",ldap.SCOPE_SUBTREE,"(objectClass=groupOfNames)",) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail"} AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "cn=G_Django_User,ou=Django,ou=<xxx>,dc=<domain>,dc=com", "is_staff": "cn=G_Django_Staff,ou=Django,ou=<xxx>,dc=<domain>,dc=com", "is_superuser": "cn=G_Django_Admin,ou=Django,ou=<xxx>,dc=<domain>,dc=com", } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( "django_auth_ldap.backend.LDAPBackend", "django.contrib.auth.backends.ModelBackend", ) Best regards Berni -
Type Error: Sum doesn't allow distinct (Django)
I am facing a problem in django, It tells me that "Sum doesn't allow distinct". It is working fine in my friends' computers but it is not working in my computer. Could you please help me? I will share screenshot also with the question. Screenshot of the error -
DoesNotExist at /add_user_save Staff matching query does not exist
DoesNotExist at /add_user_save Staff matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/add_user_save Django Version: 3.0.5 Exception Type: DoesNotExist Exception Value: Staff matching query does not exist. Exception Location: C:\Users\Shahreen Mushtaq\Envs\myproject\lib\site-packages\django\db\models\query.py in get, line 415 Python Executable: C:\Users\Shahreen Mushtaq\Envs\myproject\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\Shahreen Mushtaq\\project\\bus', 'C:\\Users\\Shahreen Mushtaq\\Envs\\myproject\\Scripts\\python38.zip', 'c:\\users\\shahreen ' 'mushtaq\\appdata\\local\\programs\\python\\python38\\DLLs', 'c:\\users\\shahree[enter image description here][1]n mushtaq\\appdata\\local\\programs\\python\\python38\\lib', 'c:\\users\\shahreen mushtaq\\appdata\\local\\programs\\python\\python38', 'C:\\Users\\Shahreen Mushtaq\\Envs\\myproject', 'C:\\Users\\Shahreen Mushtaq\\Envs\\myproject\\lib\\site-packages'] Server time: Mon, 20 Apr 2020 15:04:56 +0000 [1]: https://i.stack.imgur.com/su0RB.png -
CSS styling in Django
I linked my CSS to my template index, the Styling worked partly.. but the border settings did not apply. Here is my code. I have already checked the class name multiple times, also the border settings do not apply to h1 CSS Styling -
IntelliJ - indent Django directives in HTML?
Just thought I'd see if there was any way of doing this. Django template files contain "directives" (I think this is the right term). An example is: <div class="row"> <div class="col-md-8"> {% for message in messages %} {% if message.level_tag == 'success' %} <div class="alert alert-success">{{ message }}</div> {% else %} <div class="alert alert-warning">{{ message }}</div> {% endif %} {% endfor %} </div> </div> NB the above is an example of how a file looks after going Code --> Reformat code. ... it would be desirable to say, for example, that {% for %} indents and {% endfor %} de-indents. I had a look under File --> Settings --> Editor --> Code style --> HTML ... but I couldn't see any way of adding additional "tag/directive" strings. It looks like HTML tags are hard-coded into this formatting engine and you can't add to them. -
Docker nuxt js and django getting error (Econnrefused)
i am currently working on docker with django and nuxt js. I can get json data from https://jsonplaceholder.typicode.com/posts in asyncData or nuxtServerInit it's correctly fetching and getting no error. But when i want to fetch from my django rest api service is getting error (cors headers added). I tested to fetching posts from django rest api with created() hook and it's working. I don't understand why its getting error. my docker compse ile version: '3' networks: main: driver: bridge services: api: container_name: blog_api build: context: ./backend ports: - "8000:8000" command: > sh -c "python manage.py runserver 0.0.0.0:8000" volumes: - ./backend:/app networks: - main web: container_name: blog_web build: context: ./frontend ports: - "8080:8080" volumes: - ./frontend:/code networks: - main backend docker file FROM python:3.8-alpine ENV PYTHONBUFFERED 1 ENV PYTHONWRITEBYTECODE 1 RUN mkdir /app WORKDIR /app COPY ./requirements.txt /app/ RUN pip install -r requirements.txt EXPOSE 8000 ADD . /app frontend dockerfile FROM node:13-alpine WORKDIR /code/ COPY . . EXPOSE 8080 ENV NUXT_HOST=0.0.0.0 ENV NUXT_PORT=8080 RUN npm install CMD ["npm", "run", "dev"] Nuxt-config.js server: { port: 8080, host: '0.0.0.0' } pages/index.vue export default { asyncData(context){ return context.app.$axios.$get('http://127.0.0.1:8000') // this throwing an error .then((res) => { let posts = []; posts = res; return … -
images not loading on webpage from database using django
i have made a library web app. i am trying to make a search for searching the books from database.all other information such as title is showing except the image.below is the screenshot enter image description here below is my search.html {% extends 'bookslib/base.html' %} {% block body_block %} {% load static %} {% if books %} {% for book in books %} <div class="books"> <div class="book"> <img src="{{ book.imagefile.url }}" height="250px" width="200px"> <p>{{ book.title }}</p> </div> </div> {% endfor %} {% endif %} {% endblock %} below is search view: enter code here def search(request): if request.method == "POST": query = request.POST.get('query') if query: books = Book.objects.filter(Q(title__icontains=query) | Q(author__name__icontains=query)) if books: return render(request, 'bookslib/search.html', {'books':books}) else: return redirect('bookslib/home.html') return redirect('bookslib/home.html') i have added this path to my main project's urls.py enter code here + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my images are in media/images/ media directory is in directory where my project and app is stored. kindly help me. if you need another information please let me know. thank you in advance. -
Why is my form not being saved to the database?
Hi I'm developing a website for an online store using Django. I want to use Ajax to handle the view of my checkout form after it has been submitted. After the form is submitted, I want it to go to : return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") , i.e http://127.0.0.1:8000/checkout/?address_added=True But for some reason, it is not going there. Rather it's being redirected to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=W4iXFaxwpdtbZLyVI0ov8Uw7KWOM8Ix5GcOQ4k3Ve65KPkJwPUKyBVcE1IjL3GHa&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on As a result, the form data is also not getting saved. I was thinking if it were because of the new version of Django. What I want to do is that after they submit the place order button, the form is going to be None, i.e disapper and then I would add a credit card form there for payment. But it is not happening. What is wrong here? Can anyone please help me out of this or is there a better way to do this? My forms.py: class UserAddressForm(forms.ModelForm): class Meta: model = UserAddress fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"] My accounts.views.py: def add_user_address(request): try: next_page = request.GET.get("next") except: next_page = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if next_page is not None: return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") … -
How to sort a column by Django model method using django-sortable-listview (SortableListView)?
Using django-sortable-listview package, I'm using SortableListView to sort out all the model fields. In my case, more than model fields, I want to sort it out by model method too. Models.py class Employee(models.Model): name = models.CharField() designation = models.CharField() company = models.ForeignKey(Company) team = models.CharField() # method def team_count(self): count = len(Employee.objects.filter(team=self.team)) return count Views.py class EmployeeListView(SortableListView, generic.list.ListView): allowed_sort_fields = {'name': {'default_direction': '', 'verbose_name': 'Employee Name'}, 'designation': {'default_direction': '', 'verbose_name': 'Designation'}, 'team': {'default_direction': '', 'verbose_name': 'Team Name'}, 'team_count()': {'default_direction': '', 'verbose_name': 'No of Team members'}} default_sort_field = 'name' queryset = Employee.objects.all() paginate_by = 10 On the above example, I want to list out Employee name, designation, team name and count of team members. Anybody help me to sort 'team_count' column? -
how to iterate through an array in the Django database
Help please ) I create a local site for myself . A new user is created during registration . After that, you need to log in to your account, you just need to search for an element with the entered name and that's it . Then I don't know how to find the same element in other views . So I want that after registration at the entrance, the array is moved and this element becomes at the end , where I can easily call it using -id -
template not displaying information - django
I can't figure out why my data won't display in my user.html template. From reviewing the code it looks like everything is linked correctly. The users.html page is showing up on the website minus the information about {{ user.order_set.all }}. I have highlighted the code I believe relates to the issue. Any guidance would be greatly appreciated, thanks! user.html - html for displaying the data {% extends "fuisce/base.html" %} {% block content %} **{{ user.order_set.all }}** {% endblock content %} views.py - order from django.shortcuts import render, HttpResponseRedirect from django.urls import reverse # Create your views here. from carts.models import Cart from .models import Order from users.models import Profile from .utils import id_generator **def orders(request): context = {} template = "orders/user.html" return render(request, template, context)** def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse("cart")) new_order, created = Order.objects.get_or_create(cart=cart) if created: new_order.order_id = id_generator() new_order.save() my_p = Profile.objects.get(user=request.user) new_order.user = my_p new_order.save() if new_order.status == "Finished": # cart.delete() del request.session['cart_id'] del request.session['items_total'] return HttpResponseRedirect(reverse("cart")) context = {} template = "fuisce/about.html" return render(request, template, context) models.py - orders from django.db import models # Create your models here. from carts.models import Cart from users.models import Profile STATUS_CHOICES … -
Absolute paths on images uploaded by django-ckeditor
I am using django-rest-framework in conjuntion with django-ckeditor. I'm serving some images with absolute url-s without any problem. But images and files uploaded by ckeditor are served as relative paths, and they can't be displayed client side since it is in a different domain. Here is an example of what I'm getting: { image: "http://example.com/media/myimage.png", body: "<p><a href=\"/media/ckeditor/myfile.pdf\">download my file</a></p>" } And this is what I woul like to get: { image: "http://example.com/media/myimage.png", body: "<p><a href="http://example.com/media/ckeditor/myfile.pdf\">download my file</a></p>" } -
Slack bot sending messages two times when only one was called
Im currently building a simple web page with django that runs some code on the back. For running certaing methods, I created a slack bot. Let me explain the process From some channel, a user can type @Orchestrator help And they will receive a response with the commands the bot has. One of the commands is start_recon, so the message looks like this @Orchestrator start_recon <some_target> This is received by a endpoint called slack_in, which looks like this @csrf_exempt @require_POST def slack_input(request): data = request.body data = json.loads(data.decode()) if 'challenge' in data: return JsonResponse({'challenge': data}) response = slack_receiver.receive_bot_message(data) return HttpResponse(status=response) This then get parsed with receive_bot_message and from there the different tasks start. Expected behaviour: Both @Orchestrator help and @Orchestrator start_recon <target> send one request to the slack_in endpoint Actual behaviour @Orchestrator start_recon <target> is sending 2 identical requests but @Orchestrator help is sending one. -
Trying to resolve no such column: blog_comment.url
Once a user had logged into my site he could write a post and update it. Then I was making progress in adding functionality which allowed people to make comments. I was at the stage where I could add comments from the back end and they would be accurately displayed on the front end. Now when I try and update posts I get an error message. Originally I thought the problem was because I had not included a slug field in my class called Comments. Then I added url= models.SlugField(max_length=500, unique=True, blank=True). Do I now need to reset the database linked to this class? If so how do I achieve that? Or am I going off at a massively incorrect tangent? models.py from django.db import models from django.utils.text import slugify from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now()) author = models.ForeignKey(User, on_delete=models.CASCADE) url= models.SlugField(max_length=500, unique=True, blank=True) def save(self, *args, **kwargs): self.url= slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = … -
Is there a website or YouTube instructor that goes over Django groups and permissions? [closed]
I'm curious if anyone has a list of websites/books/youtube instructors that go over groups and permissions in Django? I will eventually be building a site that will restrict certain users to certain content. -
Are these the steps followed on setting up Django application with Ngnix & Gunicorn ? Please tell me If I am missing or wrong somewhere [closed]
User’s request comes to Ngnix. Ngnix forwards request to gunicorn through a socket (Socket A) Gunicorn sends request to django.core.handlers.wsgi through another socket (Socket B) where an application object (or callable) is created which is used by Gunicorn for every request . Then a list of request and response middleware callables is created on wsgi callable object. Request middleware is applied. If it sends a response, it is returned to the user. urlresolvers.resolve finds the view function to use. View middleware is applied. If response comes, it is sent back to the user. View function is called. It talks to models to do business logic, and renders the templates. The response middleware is applied, and response is sent back to the users -
Django ORM. Select only duplicated fields from DB
I have table in DB like this: MyTableWithValues id | user(fk to Users) | value(fk to Values) | text | something1 | something2 ... 1 | userobject1 | valueobject1 |asdasdasdasd| 123 | 12321 2 | userobject2 | valueobject50 |QWQWQWQWQWQW| 515 | 5555455 3 | userobject1 | valueobject1 |asdasdasdasd| 12345 | 123213 I need to delete all objects where are repeated fields user, value and text, but save one from them. In this example will be deleted 3rd record. How can I do this, using Django ORM? PS: try this: recs = ( MyTableWithValues.objects .order_by() .annotate(max_id=Max('id'), count_id=Count('user__id')) #.filter(count_id__gt=1) .annotate(count_values=Count('values')) #.filter(count_icd__gt=1) ) ... ... for r in recs: print(r.id, r.count_id, , r.count_values) it prints something like this: 1 1 1 2 1 1 3 1 1 ... Dispite the fact, that in database there are duplicated values. I cant understand, why Count function does not work. Can anybody help me?