Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to filter dropdown options
My case: I have a class, Father relationate with class Son (ForeignKey). In the admin, inside Father, Son is a dropdown. I want to show filters in Father table, to filter Son, with a dropdown too. And I don't find an example to do that. It's important that the answer specify the paths of the files. Thanks -
Why this code doesn't work, how do I grab a specific part of url?
I have the following url http://localhost:8000/enthusiastically-synergize-optimal-results-after-proactive-total-linkage/edit/ and would like to access that slug from this url in this function so I can use it. In class based view I could use self.kwargs.get('smthng') and grab that but don't know how do I do that here: def permission_of_user_for_posts(request): post = get_object_or_404(Blog, slug= request.GET.get('blog_slug')) if request.user.username == post.author: return True return False @user_passes_test(permission_of_user_for_posts) def blog_create(request): if request.method == 'POST': form = BlogForm(request.POST, request.FILES) if form.is_valid(): form.instance.author = request.user slug = form.instance.slug form.save() return redirect('/') form = BlogForm() context = { 'form':form, } return render(request, 'blogs/form.html', context) or is there something else that I am doing it wrong in permission_of_user_for_posts function? please help me thank you -
Logging to stdout with django under gunicorn
I want to log to stdout all django debug logs, the app is running in gunicorn using docker. Django config for logging: 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'console': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'DEBUG', # change debug level as appropiate 'propagate': True, }, } } And Im starting gunicorn with gunicorn --bind 0.0.0.0:80 --log-level "debug" --capture-output --enable-stdio-inheritance tls.wsgi -
Make a queryset in which the children meet a condition
I am building an API with Django Rest Framework and in one of my endpoints I need to return the father and the children that meet the condition active = True These are my models: class Category(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) class Product(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='products') And this is my queryset: queryset = Category.objects.filter(products__active=True) I have the serializer configured to return the categories along with their products. I would like the response to be all the categories with the only active products but it returns all the categories with the active and inactive products Any suggestions? Thank you very much -
How to pass values from view.py to index.html in Django?
I have all these variables in my view.py on Django. And I want to put in on the index.html def current_database(request): contador = Post.objects.count() myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["prueba2"] mycol = mydb["miapp_post"] template = loader.get_template('miapp/index.html') for x in mycol.find(): dominio = x['dominio'] porcentaje_movil = x['porcentaje_movil'] orportunidades_movil = x['orportunidades_movil'] diagnosticos_movil = x['diagnosticos_movil'] porcentaje_ordenador = x['porcentaje_ordenador'] oportunidades_ordenador = x['oportunidades_ordenador'] diagnosticos_ordenador = x['diagnosticos_ordenador'] return HttpResponse(template.render(dominio, porcentaje_movil, orportunidades_movil, diagnosticos_movil, porcentaje_ordenador, oportunidades_ordenador, diagnosticos_ordenador)) When i go to my index.html all go fine the conecction its fine, no problem with that, but for exmple y put: <p>Dominio: {{ dominio }}</p> or <p>Dominio: {% dominio %}</p> and I always get and error and i dont know how to pass these values to mi html. Thanks. -
Why my Sitemap show /number and not /title of my posts?
I´ve added the sitemap functionality to my blog, and it works fine. But in my /sitemap.xml file it shows not the title, but the number of the post. I tried to change the definition in my urls.py file to but then it shows some weird stuff after my domain. Maybe i have somewhere some little mistake My main urls.py file: from django.contrib import admin from django.urls import path, include from django.contrib.sitemaps.views import sitemap from blog.sitemaps import PostSitemap from blog import views as blog_views sitemaps = { 'posts': PostSitemap, } urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('<int:id>', blog_views.PostDetail, name='post'), ] My sitemaps.py file: from django.contrib.sitemaps import Sitemap from .models import Post class PostSitemap(Sitemap): def items(self): return Post.objects.all() My models.py file: from django.urls import reverse def get_absolute_url(self): return reverse('post', args=[str(self.id)]) -
How can I add a <name> to my Django URL path?
I have some interview data for a set of companies. For the url path, I'd like to mention the company name in addition to the interview id in the url path. Sounds easy, but I keep getting an error. In my models.py file, company is: company = models.CharField(max_length=100, verbose_name= _('Company')) My url path is: path('/interview/<slug:company>/<int:pk>', views.int_details, name='interview-detail') For my views.int_details, I've included the company and pk values in the parameters: def int_details(request, company, pk): ... The error message is: Reverse for 'interview-detail' with arguments '(7,)' not found. 1 pattern(s) tried: ['experiences\\/interview\\/(?P<company>[-a-zA-Z0-9_]+)\\/(?P<pk>[0-9]+)$'] Where 7 is the interview id value. If I don't have the company variable mentioned in the url, the link works fine. What breaks it is the <slug:company> addition. I don't know if having slug in front of company helps. I noticed it was used in the Django docs, so I ran with it. -
how to check the performance of raspberry pi
I made raspberry pi as a web server using Django. How to find its performance like CPU usage, disk usage, time etc.. as the number of users increases. I tried ps aux but it gives the same %cpu as users increases. -
How to convert sql query to django orm query?
We are django and sql, so we have written query in sql , here my request is how can I convert sql query to django query.Please let me know -
img src not working in Django using Bootstrap Carousel
Im trying to add an image to my bootstrap carousel but image is not loading. {% extends 'base.html' %} {% block html %} {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> </head> <body> <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="/Users/myname/Documents/django/ldn/static/images/phone.jpg" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="{% static 'static/images/network.jpg' %}" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="../static/images/phone.jpg" alt="Third slide"> </div> </div> </div> </body> </html> {% endblock %} Ive tried various methods as shown above but none work. My static/images folder is in my project root. Thanks -
Problem with uncontrolled modify every time data is saved in django slug
I want to create unique slug.I want to create unique slug. I use some methods to generate unique slug,but I have problem with them. this is my model and my method to create unique slug: #Models.py class MyModel(models.Model): slug = models.SlugField(null=True, blank=True, unique=True) def _get_unique_slug(self, slug_input): slug = slugify(slug_input) unique_slug = slug num = 1 while Curriculum.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.id: # Create if not self.slug: # slug is blank self.slug = self._get_unique_slug(slug_input=self.title) else: # slug is not blank self.slug = self._get_unique_slug(slug_input=self.slug) else: # Update self.slug = self._get_unique_slug(slug_input=self.slug) super(Curriculum, self).save(*args, **kwargs) This method have two problem: 1. Every time that I save each object(even without modify it), slug changes and '-1' append to it. 2. For some language such as Arabic and Farsi(Persian) slug didn't create. how can I fix these problems? -
Django pagination returns all data after clicking any page number in search result
I paginated the search result. For the first, query set gives me perfect result , but when i click on any page number, it accepts search key as null and get all data from db. here is the code Views.py def youtube_search(request): query = request.GET.get('q') Q = SearchDetail.objects.all().filter(query = query).order_by('-datetime') if request.method=='GET': page_request_var = 'page' page = request.GET.get(page_request_var) paginator = Paginator(Q, 10) try: paginated_queryset = paginator.page(page) except PageNotAnInteger: paginated_queryset = paginator.page(1) except EmptyPage: paginated_queryset = paginator.page(paginator.num_pages) context = { 'queryset': paginated_queryset, 'page_request_var': page_request_var, 'searchKey':query } return render(request, 'home.html', context) here is my template Home.html <!DOCTYPE html> <html> <body> <header> <h3 class="h6">Search the blog</h3> </header> <form action="{% url 'search' %}" class="search-form"> <div class="form-group"> <input type="text" name="q" placeholder="What are you looking for?"> <button type="submit">search</button> </div> </form> {% for Q in queryset %} {{Q.title}}<br/> {{Q.description}}<br/> {{Q.datetime}}<br/> {{Q.thumbnail}}<br/> {% endfor %} <nav aria-label="Page navigation example"> <ul class="pagination pagination-template d-flex justify-content-center"> {% if queryset.has_previous %} <li class="page-item"><a href="?{{ page_request_var }}={{ queryset.previous_page_number }}" class="page-link"> <i class="fa fa-angle-left"></i></a></li> {% endif %} {% for num in queryset.paginator.page_range %} {% if queryset.number == num %} <li class="page-item"><a href="?{{ page_request_var }}={{ queryset.number }}" class="page-link active">{{ num }}</a></li> {% elif num > queryset.number|add:'-3' and num < queryset.number|add:'3' %} <li class="page-item"><a href="?{{ … -
do you know how to get array in view function? An error occurred when passing array
i tried below code and get error for view function Please let us know the cause of the error and how to fix it. error message Internal Server Error: /todo/todo_delete_ajax/ Traceback (most recent call last): File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view todo.views.todo_delete_ajax didn't return an HttpResponse object. It returned None instead. jquery , ajax $('#todo_delete_button').click(function(e){ e.preventDefault(); // todo_check var todo_arr = []; alert("삭제 버튼 ") // Get checked checkboxes $('.td_check').each(function() { if (jQuery(this).is(":checked")) { var id = this.id; // alert("id : " +id) todo_arr.push(id); } }); alert('todo_arr : '+ todo_arr) // todo_arr : 78,76 $.ajax({ type: "POST", url: 'todo_delete_ajax/', data: { todo_arr:todo_arr, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(result) { alert('todo_delete_ajax is success '); } }); }) view def todo_delete_ajax(request): print("request " , request ) do you know how to get array in view function ? thanks for let me know ~! -
How to set custom filter in URL in Django Rest Framework?
I am using Django Rest Framework 3.9.4. Currently I am just using it to create API sort of an abstracted layer over my MongoDB setup. So technically I just use helper functions and call it using DRF viewset to return the result from MongoDB. During my research I came across the following articles related to filtering. Is there any way I can set up a custom filter like for url : e.g /peakhours/?type=voip&date_gte=<date>&date_lte=<date>. Please note I don't have models written it's just a wrapper over my MongoDB setup. Hope I am clear with my question. Any help will be appreciated. TIA -
Remove spotcolor layer from pdf
I try to make thumbnails of PDF-files. In the past i had a little bug, which did the thing, but I can't reproduce my bug anymore ;) while converting the pdf to png the transparency was wrong, which let me look through the toplayer. The problem is that in the pdf we have a layer with a spotcolor "white" on it. If i create a thumbnail I only see this layer. I would like to remove or deactivate this layer before creating the thumbnails. In Acrobat we can do this by unchecking a checkbox.. is there something in python which can do this job? best regards -
How to change 'timeout' in "zappa_settings.json" file
So i deployed my django project on AWS account through Zappa. Then i added the 'timeout_seconds' parameter and set it to 300 in zappa_settings.json. On running 'zappa update dev', it gives the following error: "botocore.exceptions.ParamValidationError: Parameter validation failed: Invalid type for parameter Timeout, value: Â 300,, type: , valid types: " I want to increase the timeout of the lambda function to 300 seconds. Here is the full error traceback: (venv) C:\Users\tansingh\Downloads\PriceAPP\Code & Sample Input\Aws_pricing>zappa update dev (s3transfer 0.2.0 (c:\users\tansingh\downloads\priceapp\code & sample input\aws_pricing\venv\lib\site-packages), Requirement.parse('s3transfer<0.2.0,>=0.1.10'), {'boto3'}) Calling update for stage dev.. Downloading and installing dependencies.. - pandas==0.23.3: Using locally cached manylinux wheel - numpy==1.14.5: Using locally cached manylinux wheel - sqlite==python3: Using precompiled lambda package 'python3.7' Packaging project as zip. Uploading aws-pricing-app-dev-1559297372.zip (36.9MiB).. 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 38.7M/38.7M [00:07<00:00, 3.52MB/s] Updating Lambda function code.. Updating Lambda function configuration.. Oh no! An error occurred! :( ============== Traceback (most recent call last): File "c:\users\tansingh\downloads\priceapp\code & sample input\aws_pricing\venv\lib\site-packages\zappa\cli.py", line 2779, in handle sys.exit(cli.handle()) File "c:\users\tansingh\downloads\priceapp\code & sample input\aws_pricing\venv\lib\site-packages\zappa\cli.py", line 509, in handle self.dispatch_command(self.command, stage) File "c:\users\tansingh\downloads\priceapp\code & sample input\aws_pricing\venv\lib\site-packages\zappa\cli.py", line 556, in dispatch_command self.update(self.vargs['zip'], self.vargs['no_upload']) File "c:\users\tansingh\downloads\priceapp\code & sample input\aws_pricing\venv\lib\site-packages\zappa\cli.py", line 970, in update aws_kms_key_arn=self.aws_kms_key_arn File "c:\users\tansingh\downloads\priceapp\code & sample input\aws_pricing\venv\lib\site-packages\zappa\core.py", line 1223, in update_lambda_configuration 'Mode': 'Active' if … -
Django internationalization: prefix_default_language & language redirect
I'm adding internationalization to my Django project. The idea of how it should work is the following: When a user enters "/" i.e. the "homepage" we try to get his/her language preferences from our session. If it's not our default language (EN), we redirect the user to the local version, like /ES/, /RU/, /CN/, etc If we have no such session data, we check Accept-Language and redirect the user to the local version if we support such If we don't support user's Accept-Language OR if it's EN - we don't redirect user! we just show the "default language" I.e. all "not default languages" should have their prefixes, but default one won't. Why the default language should have a prefix, right? ))) The issue is, I can't figure out how to set this logic. If I set prefix_default_language=False to disable the /EN/ prefix for default language, it also disables the "not default" redirect. I found a package that solves the problem: https://github.com/st4lk/django-solid-i18n-urls#behaviour settings.SOLID_I18N_USE_REDIRECTS = True but it doesn't work in Django 2+ I can't believe I'm the only one hating the default language prefixes )) Although I could not find any solution with both redirect and no prefix for the default … -
Getting an error 'redirect' on views.py of django project
All the registration form is running fine.The problem is on the redirect of function addUser.I am getting the error on redirect.I am trying to save the data in the admin panel but i am stuck on this. from django.shortcuts import render,redirect from django.http import HttpResponse from .forms import RegistrationForm from .models import RegistrationData #from django.contrib.auth.form import UserCreationForm # Create your views here. def index(request): return render(request, "Yatri/home.html") def SignUp(request): context= {"form":RegistrationForm} return render(request,"Yatri/register.html",context) def addUser(request): form=RegistrationForm(request.POST) if form.is_valid(): register=RegistrationData(username=form.cleaned_data['username'], password=form.cleaned_data['password'], email=form.cleaned_data['email'], phone=form.cleaned_data['phone'], register.save() return redirect('index') I expect the username,password,email and phone to be saved in database but i get the error the site cant be reached. -
How do I implement UserPassesTestMixin in function based views?
I can implement UserPassesTestMixin in class based views, class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False but I don't know how to implement this in function based view? Thank you -
Django: Stream video to multiple users
Hi I'm new to django and I'm trying to stream a video to multiple users at the same time. It should work like the website Watch2Gether. The user should be able to join a session where it shows the video. Things like pause and play should also work for every user in the session. At the moment I only have a simple site where one user can watch a video loaded by <video> Does anyone has an idea how I could accomplish that? I'm grateful for every help. Feel free to ask questions if something is not clear. -
Properly assembling a drinks database with Django (Many to Many)
I would like to set up a drink database, now I have the problem that the databases are not generated accordingly and I do not know how to do this. i have already tried several things, but unfortunately no solution was found how the database should look like: Table 1 (Drinks) ----------------------------------------------------------- drink_Id | drink_name | description | image_path | slug | ----------------------------------------------------------- Table 2 (ingredients) --------------------------------- ingredient_id | ingredient_name | --------------------------------- Table 3 (drink_ratio) --------------------- ID_ratio | quantity | --------------------- Table 4 () ----------------------------------------- id | drink_id | ingredient_id | ID_ratio | ----------------------------------------- Code: from django.db import models class Drinks(models.Model): drink_name = models.CharField(max_length=256, unique=True) description = models.TextField() image_path = models.ImageField(upload_to="./images") slug = models.SlugField(unique=True) ingredient = models.ManyToManyField('ingredient') def __str__(self): return self.drink_name class ingredient(models.Model): name = models.CharField(max_length=256, unique=True) liquid_ratio = models.ManyToManyField('liquid_ratio') def __str__(self): return self.name class liquid_ratio(models.Model): quantity = models.DecimalField(max_digits=4, decimal_places=2, unique=True) I want to achieve that I have only 4 tables. like at the top. A drink can have several ingredients. A drink can only exist once. A drink can only have one quantity per ingredient. THANK YOU :)) -
How to POST multiple list of fields data to child model along with parent model
I have two models Visit(parent model) and VisitAccessories(Child Model). when i Post(VisitAccessories) data only last element of the list get added and record gets created. but others element are ignored. serializer.py class VisitAccessoriesSerializers(serializers.ModelSerializer): class Meta: model = VisitAccessories exclude = ("visit",)#visit is foregin key to visit model class ListAccessoriesSerializers(serializers.ModelSerializer): visit_accessories = VisitAccessoriesSerializers(many=True,source='visitaccessories_set', required=False,) class Meta: model = VisitAccessories exclude = ("visit",) #visit is foregin key to visit model class VisitSerializers(serializers.ModelSerializer): visit_accessories = VisitAccessoriesSerializers(many=True, source='visitaccessories_set', required=False) class Meta: model = Visit fields = ('__all__') views.py def post(self, request): serializer = VisitSerializers(data=request.data) accessories_serializer = ListAccessoriesSerializers(data=request.data) if serializer.is_valid(raise_exception=ValueError) and accessories_serializer.is_valid(raise_exception=ValueError): visit_obj = serializer.save() # Visit Created accessories_serializer.save(visit=visit_obj) # VisitAccessories return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST) -
How do I access a Python created dictionary
I have followed the code here https://docs.microsoft.com/en-us/outlook/rest/python-tutorialnd and it works however I need to access the calender events for my own purpose. context = { 'events': events['value'] } return render(request, 'tutorial/events.html', context) The HTML is <table class="table"> <tr> <th>Subject</th> <th>Start</th> <th>End</th> </tr> {% for event in events %} <tr> <td>{{ event.subject }}</td> <td>{{ event.start.dateTime }} ({{ event.start.timeZone }})</td> <td>{{ event.end.dateTime }} ({{ event.end.timeZone }})</td> </tr> {% endfor %} </table> My question is how can I interrogate context to obtain the data in the format shown above? Ie subject start date time and end date time. I'm very new to Python. I've seen how the data is held using debug statements. See above I need interrogate context to obtain the data in the format shown above? Ie subject start date time and end date time. -
Unable to store hashed password in database in django
I am using custom user model by extending AbstractBaseUser . However inspite of calling set_password inside custom user manager I am unable to store hashed password in my postgres database. I followed the solution given at the below link but it didn't work:- Django: set_password isn't hashing passwords? Folloing is my code for models and managers models.py from django.contrib.auth.models import PermissionsMixin from django.contrib.gis.db import models from django.contrib.auth.base_user import AbstractBaseUser from .managers import InterestedUserManager # Create your models here. class User(AbstractBaseUser, PermissionsMixin): date = models.DateTimeField(auto_now_add=True, null=True, blank=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(blank=False, unique=True) phone_no = models.CharField(max_length=10, blank=False) address = models.CharField(max_length=100, blank=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = ('user') verbose_name_plural = ('users') def __str__(self): return "%s %s -- %s" % (self.first_name, self.last_name, self.address) managers.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email, **extra_fields) user.set_password(password) user.save(using=self._db) print("User object is ",user) print("User password is ".user.password) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not … -
how to fix "Unable to import 'faker' pylint(import-error)" in VSCode running a populate file in django
i want to run a populating script in django but i got pylint error before running in terminal. 1- Unable to import 'faker'pylint(import-error) 2- Class 'Topic' has no 'objects' memberpylint(no-member) that is the same for webpage and accessrecord... i dont know what the problem is... when i run it in terminal with command "python populate_first_app.py" i get this errors: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. this is part of my code : import os import django from first_app.models import Topic, Webpage, AccessRecord from faker import Faker import random from first_project import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') django.setup() fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): ''' Create N Entries of Dates Accessed ''' for entry in range(N): # Get Topic for Entry top = add_topic() # Create Fake Data for entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create new Webpage Entry webpg = Webpage.objects.get_or_create( topic=top, url=fake_url, name=fake_name)[0] ...