Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generate a function-based index in my Python model migration?
I'm using Django, Python 3.7 and PostGres 9.5. To speed along a particular query, I want to create this functional index, which I'd normally do in PostGres like so ... CREATE INDEX my_article_idx ON article (regexp_replace(url, '\?.*$', '')) However in the world of Django and auto-generated migrations, I'm not sure how to annotate my class in my models.py file so that this function-based index would be auto-generated. The field in question in my model looks like this ... class Article(models.Model): ... url = models.TextField(default='', null=False) -
What is the difference between annotations and regular lookups using Django's JSONField?
You can query Django's JSONField, either by direct lookup, or by using annotations. Now I realize if you annotate a field, you can all sorts of complex queries, but for the very basic query, which one is actually the preferred method? Example: Lets say I have model like so class Document(models.Model): data = JSONField() And then I store an object using the following command: >>> Document.objects.create(data={'name': 'Foo', 'age': 24}) Now, the query I want is the most basic: Find all documents where data__name is 'Foo'. I can do this 2 ways, one using annotation, and one without, like so: >>> from django.db.models.expressions import RawSQL >>> Document.objects.filter(data__name='Foo') >>> Document.objects.annotate(name = RawSQL("(data->>'name')::text", [])).filter(name='Foo') So what exactly is the difference? And if I can make basic queries, why do I need to annotate? Provided of course I am not going to make complex queries. -
MultiValueDictKeyError at /upload/
i need some help with Django, i keep encounter the MultiValueDictKeyError when i click the download button. And it shows MultiValueDictKeyError at /upload/ 'my_file' but not sure how to solve it after several attempts. Below are my codes for models, view, and the template page. For your advice please. models.py class File(models.Model): upload = models.FileField(upload_to='files') location = models.CharField(max_length=500, null=True) file_type = models.CharField(max_length=100, null=True) size = models.IntegerField(null=True) upload_datetime = models.DateTimeField(auto_now=True) def __str__(self): return self.upload.name def pre_save_file_info(sender, instance, *args,**kwargs): instance.location = instance.upload.url instance.size = instance.upload.size pre_save.connect(pre_save_file_info, sender=File) views.py def files_upload(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['my_file'] if uploaded_file.content_type not in file_content_types: print("INVALID CONTENT TYPE") else: new_file = File(upload=uploaded_file, file_type=uploaded_file.content_type) new_file.save() print(uploaded_file.content_type) qs = File.objects.all().order_by('-upload_datetime') context['files'] = qs context["file_types"] = file_content_types file_type_counts = [] for file_type in file_content_types: count = File.objects.filter(file_type=file_type).count() file_type_counts.append(count) context["file_type_counts"] = file_type_counts return render(request, "files_ul_dl.html", context) def download_view(request): if request.method == 'POST': path = request.POST.get('path') print(path) file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/force-download") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 -
Django Template is Printing Object Representation instead of Object Value
views.py @login_required def ManageDomain(request): AssocNotAuthDomains = Tld.objects.filter(FKtoUser_id=request.user,auth=0) AssocAuthDomains = Tld.objects.filter(FKtoUser_id=request.user,auth=1) return render(request, 'site/account/template.html', { 'AssocNotAuthDomains':AssocNotAuthDomains, 'AssocAuthDomains':AssocAuthDomains }) template.html {% if AssocAuthDomains or AssocNotAuthDomains %} <div class="acctDomains"> <h3 class="Titles"><img src="{% static "img/templated/acct/AuthDomainSm.png" %}" width="22" height="22" alt="Authorized Domain(s)" /> Verified Domains</h3> <ul> {% for authdomain in AssocAuthDomains %} <li>{{ authdomain }}<span><a class="scan" href="/Account/PerformScan/?d={{ authdomain }}">Scan now</span></a></li> {% endfor %} </ul> <h3 class="Titles"><img src="{% static "img/templated/acct/UnAuthDomain.png" %}" width="22" height="22" alt="Unverified Domain(s):" /> Unverified Domains</h3> <ul> {% for notauthdomain in AssocNotAuthDomains %} <li>{{ notauthdomain }}<span><a class="scan" href="Verify Now">Verify now</span></a></li> {% endfor %} </ul> </div><!--acctDomains--> This prints out: Tld object (1) Tld object (2) instead of the value e.g. websiteabc.com What am I doing wrong? Thanks -
Method Not Allowed: / (Django-Post Method)
When I submit the form, it says "Method Not Allowed: /" in the console.. Something like that: Method Not Allowed: / [17/Mar/2019 18:31:18] "POST / HTTP/1.1" 405 I'm using this on views.py file.. class UrlAccpt(View): template_name='phc/url_accpt.html' def get(self,request): urlx='' form = UrlForm(request.POST) if request.method == 'POST': form = UrlForm(request.POST) if form.is_valid(): urlx= form.cleaned_data['EnterTheUrl'] form = UrlForm(request.POST) response = TemplateResponse(request,self.template_name,{'form':form,'value':urlx}) return response and in forms.py file...I use this code from django import forms class UrlForm(forms.Form): EnterTheUrl=forms.CharField(max_length=1000) -
How do I write my Django query when the WHERE clause is meant to have a function?
I'm using Django and Python 3.7 along with PostGres 9.5. I have a column in my PostGres table of type text, which records URLs for articles. I want to run a query that compares everything before the query string, e.g. SELECT * FROM article where regexp_replace(url, '\?.*$', '') = :url_wo_query_info but I'm not sure how to pull this off in Django. Normally if I want to straigh tup query on just a URL, I could write Article.objects.filter(url=url) BUt I'm unsure how to do the above in Django's lingo because there is a more complicated function involved. -
Assign a rank to a movie based on number of comments - Django
I have movies, each movie has comments added to it. I want to create a function that will rank my Movies based on a number of comments using dense ranking. This is what I got so far - the problem is, every movie always has rank 1. commented_movies = Movie.objects.annotate(comment_count=Count('comments', distinct=True)).annotate( rank=Window(expression=DenseRank() , order_by=F('comment_count').desc() , partition_by=[F('id')])) I guess the problem might be in partition_by, but I have no idea how to solve it. id is a primary key of the Movie. -
Error trying to diff '[object Object]'. Only arrays and iterables
i dont know why i get this error. It is in AppComponent.html:4 Error trying to diff '[object Object]'. Only arrays and iterables are allowed app.component.html <h2>Movies</h2> <ul> <li *ngFor='let movie of movies'> <h2>{{movie.title}}</h2> </li> </ul> app.component.ts import {Component} from '@angular/core'; import {ApiService} from './api.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [ApiService] }) export class AppComponent { movies = [{title: 'test'}]; constructor(private api: ApiService) { this.getMovies(); } getMovies = () => { this.api.getAllMovies().subscribe( data => { this.movies = data; }, error1 => { console.log('error'); } ); }; } app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import {HttpClientModule} from '@angular/common/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Can you tell me what im doing wrong? -
Create multiple model instances of interlinked models through one post request in DRF
I want to create two entries from one post request. One in the 'Dates' model and one in 'Other' model. Code corresponding to both models is shown below. class Dates(models.Model): booking_id = models.AutoField(primary_key=True) timestamp = models.DateTimeField(auto_now_add=True) feedback = models.CharField(max_length=8, default='no') myself = models.BooleanField(default=True) class Meta: app_label = 'bookings' Other is: class Other(models.Model): booking_id = models.OneToOneField( 'bookings.Dates', null=False, default=1, primary_key=True, on_delete=models.CASCADE ) name = models.CharField(max_length=64) phone_number = models.CharField(max_length=14) email_id = models.EmailField(max_length=128) class Meta: app_label = 'bookings' I have validated the data from Dates Serializer and created the object in 'Dates' table. Now, I want to use the generated 'booking_id' as the same 'booking_id' for 'Other' table. How can I validate serializer and create an object in the 'Other' table while maintaining the consistency? Here with consistency, I mean: Either create objects in both the tables if no error occurs or don't create an object if any error occurs. -
After deploy django app in digitalocean i can't see my changes in server?
I was deploy my webapp in digitalocean which is written by django. Now i change and add some file in it. I change the template folder and also add some photos in static folder. After change i pull the changes from github in my server app directory. But i can't see the changes. I stop the nginx server. I use this command sudo systemctl start nginx sudo systemctl stop nginx sudo systemctl restart nginx then again i start but no changes. what should i do? -
'FileDescriptor' object has no attribute 'path'
When uploading a file in Django's admin, I'm trying to create and rename a copy of this file using a signal. However, I'm receiving the following error: 'FileDescriptor' object has no attribute 'path' models class Template(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) name = models.CharField(max_length=255) def org_folder(self, filename): path = "templates/%s/%s/%s" % (self.organization.name, self.name, filename) return path docxfile = models.FileField(upload_to=org_folder) signals @receiver(post_save, sender=Template) def create_clean_docxfile(sender, instance, *args, **kwargs): if sender is Template: file = Template.docxfile.path copyfile(file, 'temp.zip') Any recommendations? -
Creating a Order Menu In Django
I'm Trying to create a menu for Canteen where the product name and price is being updated/added by the admin . But how do i retrieve the ordered items by the customer ? <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">Item Name</th> <th scope="col">Item Price</th> <th scope="col">Item Type</th> <th scope="col">Quantity</th> </tr> </thead> {% for temp in food_dict %} <tr> <td>{{ temp.food_name }}</td> <td>{{ temp.food_price }}</td> <td>{{ temp.type }}</td> <td> <input type="button" onclick="dec({{ forloop.counter }})" class="btn btn-light" value="-"/> <input type="button" id="{{ forloop.counter }}" name="temp.food_name" class="btn btn-light" value="0"/> <input type="button" onclick="inc({{ forloop.counter }})" class="btn btn-light" value="+" /> {{ temp.food_name }} </td> </tr>`enter code here` {% endfor %} {% endif %} </table> -
Paginator isn't functioning at all
I'm trying to use a paginator for a project I'm making and I don't see what's wrong with my code but the list isn't getting paginated. from django.core.paginator import Paginator def BlogsList(request): blogs=Blog.objects.all() paginator = Paginator(blogs, 5) context={ 'blogs':blogs } return render(request, 'blog/home.html',context) -
Django, how to use CreateView and UpdateView to add two records at the same time
I need a model with some FloatField feilds, each records of this table should be used with another one (first row indicate minimum and the second one determine maximum). I like the values of these two rows be added or edited simultaneously by user. I'm eager to know how to use django CreateView and UpdateView generic classes for this purpose. Please let me know your helpful comments. -
Injecting class properties via decorators
I have a whole bunch of Django TestCases that use the setUp method to initialize some properties that are used throughout numerous tests, the way they're constructed and depend on each other is logic I want to move out of the test cases and reuse def setUp(self): self.property_1 = ##some logic ... I wanted to rewrite these as some convenience wrapper that could be injected into the class with a simple inheritance or decorator, e.g. @with_property_1(x=1, y=2) def setUp(self): ... def with_property_1(**model_kwargs): def wrapper(f): def wrapped(*args, **kwargs): self.property_1 = ## logic f(*args, **kwargs) return wrapped return wrapper but the trouble is that PyCharm doesn't recognize that those instance properties exist because nothing inside the TestCase class proper ever sets them. Is there a either another way I can achieve this nicely, or a way to cajole PyCharm into recognizing these properties are legitimate given the existence of the decorator? -
Django queryset get all fields in values() plus a foreign key field
I have a model with some fields, one of them is a FK. I would like to use MyModel.objects.all().defer("pk").values() and to add a field of my FK (myfk__name) without writing all model fields + 1 in the values. I also would like to avoid doing another query after this one to add it manually. Is it possible? -
Display pagination using html only in django
Can I apply pagination using this index.html page only and without using the views.py I wrote some lines in django like below in index.html <!DOCTYPE html> <html> <head> <title></title> </head> <body> <table align="center" class="productTable"> <thead> <tr> <th>NAME</th> <th>MARKS</th> <th>SUBJECT</th> <th>DATE</th> </tr> </thead> </tr> {% for item in contacts %} <tr> <td>{{ item.sid }}</td> <td>{{ item.marks }}</td> <td>{{ item.subject }}</td> <td>{{ item.tdate }}</td> </tr> {% endfor %} </table> <center> <div class="pagination"> <span class="step-links"> {% if contacts.has_previous %} <b><a href="?page={{ contacts.previous_page_number }}">previous</a><b> {% endif %} <span class="current"> <b> Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.</b> </span> {% if contacts.has_next %} <a href="?page={{ contacts.next_page_number }}">next</a> {% endif %} </span> </div> </center> </body> </html> I wrote this but pagination is not applied please help I am trying this out to to this using index.html page only but not able to do this -
Django in template using if tag compare one variable with a number always give false
I first use widthratio tag to calculate a ratio percentage number and assgign it to a variable named Ratio Then when I try to compare it with an integer in if and elif tag, I alway go to the final else tag and get the wrong result. Below is my source code: <div class="container-fluid"> <p><span class="icon-group"></span> Player registratered: {{event.Players_registratered}}/{{event.Max_players}}</p> {% widthratio event.Players_registratered event.Max_players 100 as Ratio %} {{Ratio}} <div class="progress progress-striped active text-center"> {% if Ratio < 30 %} <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width:{{Ratio}}%"> </div> {% elif Ratio < 70 %} <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width:{{Ratio}}%"> </div> {% elif Ratio < 90 %} <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width:{{Ratio}}%"> </div> {% else %} <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width:{{Ratio}}%"> </div> {% endif %} </div> </div> and the output snip:Wrong output I hope someone could answer it. Thank you very much. -
Django Incomplete response received from application while using sendmail() function
I have built an app on Django 2.0 and deployed to pythonanywhere.com. As Pythonanywhere.com hosting does not have SMTP server, I used external server (used hostiq.com SMPT server, where I have other websites hosted) to send messages using views. Everything worked fine, except the price :) So I moved the app to reg.ru hosting (because it is cheap and has SMTP server). The web app works fine, except the links that send mails. All the veiws functions that use sending mails, fail and give an error "Incomplete response received from application". You can test it yourself by following the link: http://www.tajadventures.com/contact-us/ More information which may be useful to solve the problem: 1) I have two apps in a shared hosting reg.ru. 2) I use virtual environment on the server; 3) The Customer Support says that using PROXY (like this Working with django : Proxy setup ) is NOT ALLOWED in shared hosting. Is there any way to fix this bug? Thanks is advance for your time. -
Django filter a queryset based on the template name
In my Django App, I have 2 models. One called Post and one called Categories. When a user clicks on a category, I want only the posts that are in that category to appear in the category detail view. For example if a user clicks on the medical category, I only want the posts in the medical category to appear. Models: class Category(models.Model): title = models.CharField(max_length=200) colorcode = models.CharField(max_length=20, blank=True, null=True) description = models.TextField() image = models.ImageField(blank=True, null=True) slug = models.SlugField(unique=True) class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() sub_description = models.TextField(blank=True, null=True) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) image = models.ImageField(blank=True, null=True) live = models.BooleanField(default=False) slug = models.SlugField(unique=True) Views: class CategoryDetailView(DetailView): model = Category def get_context_data(self, **kwargs): context = super(CategoryDetailView, self).get_context_data(**kwargs) context['category_posts'] = Post.objects.filter(live=True) return context Template: {% for post in category_posts %} <div class="post"> <div class="post-title"> {{ post.title }} </div> <div class="post-author"> {{ post.author }} </div> </div> {% endfor %} -
How to pass data into bootstrap modal django
I have a loop in a django template which iterates over objects. With every object I have an edit button which triggers a modal. I am passing id to every edit button which triggers the modal of that object id. Modal is opening but problem is I'm not able to pass data of the object into the modal. template {% if prof %} <table class="table"> <tbody> {% for edu in prof.education.all %} <tr class="divbutton" style="height: 90px;"> <td> <div class="row"> <div style="padding-left: 40px; font-size: 20px;">{{ edu.degree }}</div> <div style="padding-left: 40px; font-size: 20px;">{{ edu.school }}</div> </div> </td> <td></td> <td class="align-middle"> <div class="row"> <div id="button_under" style="margin-right: 20px;" class="login login-button"> {# <button class="btn btn-info js-update-book" data-url="{% url 'users:book_update' pk=edu.id %}" style="cursor:pointer;"><i class="fa fa-edit"></i> Edit</button>#} <button class="btn btn-info" type="button" data-toggle="modal" data-target="#{{ edu.id }}" data-backdrop="false" style="cursor:pointer;"><i class="fa fa-edit"></i> Edit</button> <!-- --------------------------- Update Modal--------------------- --> <form action="{% url 'users:book_update' pk=edu.id %}" style="padding-left: 15px; padding-right:15px;" method="POST"> {{ form.errors }} {% csrf_token %} <div class="row"> <div id="{{ edu.id }}" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Update Education</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <div class="row"> <div class="col-lg-12"> <div class="form-group"> <div class="field"> <label>Degree title<span class="red-txt">*</span></label> <!-- <input class="form-control" type="text" name="degree" value="" maxlength="60" size="50"> --> {{ … -
Django - template not being detected
I'm using this library to handle two factor auth for a django project, but i'm having some troubles: in my site, i added a setup.html page, i set the url on my urls.py file but i keep getting this error: In template C:\Users\Us\lib\site-packages\allauth\templates\base.html, error at line 26 Reverse for 'account_email' not found. 'account_email' is not a valid view function or pattern name. <li><a href="{% url 'account_email' %}">Change E-mail</a></li> Which is completely weird because i'm not trying to load a file called base.html but my own setup.html file, which is located in my project's folder (the path is project-folder>templates>setup.html). It looks like the module that i'm using, instead of loading MY setup.html will load something else, but i can't find a way to fix this. Here is the view that i'm calling to handle the setup (it' the module's view): https://github.com/percipient/django-allauth-2fa/blob/master/allauth_2fa/views.py And here is my own urls.py, where the view that i mentioned is being called: from django.urls import path from . import views from django.conf.urls import url, include from django.conf.urls import url from allauth_2fa import views as allauth_2fa_views app_name = "main" urlpatterns = [ path("setup/", allauth_2fa_views.TwoFactorSetup.as_view(), name="setup"), path("", views.homepage, name="homepage"), path("register/", views.register, name="register"), path("logout/", views.logout_request, name="logout"), path("login/", views.login_request, name="login"), ] -
angular not displaying object attributes
I am following the HeroTutorial but using a Django backend. I have an Hero object that I am getting from DRF endpoint (verified with Postman). In my hero-detail.html the hero.name and hero.id are not displaying anything. I know the hero object is being passed to the hero-detail.html because the browser shows the "Details" and "id:" so the line <div *ngIf="hero"> is telling me that there is a hero.. But if there is a hero why does hero.name not show anything? There are no errors in the browser console. The link to get to the hero-detail.component is coming from a dashboard.component which uses the same method but for some reason hero.name and hero.number work fine. The dashboard.component.html displays correctly so I know my services are working fine. My hero-detail.html <div *ngIf="hero"> <h2>{{hero.name | uppercase}} Details</h2> <div><span>id: </span>{{hero.number}}</div> <div> <label>name: <input [(ngModel)]="hero.name" placeholder="name"> </label> </div> </div> <button (click)="goBack()">go back</button> hero-detail.component import { Component, OnInit, Input } from '@angular/core'; import { Hero } from '../hero' import { ActivatedRoute } from '@angular/router'; import { Location } from '@angular/common'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-hero-detail', templateUrl: './hero-detail.component.html', styleUrls: ['./hero-detail.component.scss'] }) export class HeroDetailComponent implements OnInit { constructor( private route: ActivatedRoute, private heroService: … -
How to properly validate form submission using Django
Am learning django for the first time. Here am trying to submit form data to database and the code is working great. Here is my views.py from django.shortcuts import render, redirect, HttpResponseRedirect from .models import Member # Create your views here. #proces form data def index(request): if request.method == 'POST': member = Member(username=request.POST['username'], password=request.POST['password'], confirmPassword=request.POST['confirmPassword'], email=request.POST['email']) member.save() return redirect('/') else: return render(request, 'web/index.html') here is models.py from django.db import models # Create your models here. class Member(models.Model): username=models.CharField(max_length=30) password=models.CharField(max_length=12) confirmPassword=models.CharField(max_length=12) email=models.CharField(max_length=30) def __str__(self): return self.username + " " + self.email here is index.html {% extends 'web/base.html' %} {% block body %} <form method="POST"> {% csrf_token %} <input type="text" name="username" id="username"/> <input type="password" name="password" id="password"/> <input type="password" name="confirmPassword" id="confirmPassword"/> <input type="text" name="email" id="email"/> <button type="submit"> Submit</button> </form> {% endblock %} Here is what I want to add: Now I want to validate data before submission using cleaned_data[] method and also check that the password and confirm password matched prior to form submission but am getting the error below identationError; expected an idented block. I have referenced solution found here but with no luck link Here is what I have tried to that effect. can someone help me out... #proces form data … -
Store user-defined filters in database
I need to allow users to create and store filters for one of my models. The only decent idea I came up with is something like this: class MyModel(models.Model): field1 = models.CharField() field2 = models.CharField() class MyModelFilter(models.Model): owner = models.ForeignKey('User', on_delete=models.CASCADE, verbose_name=_('Filter owner')) filter = models.TextField(_('JSON-defined filter'), blank=False) So the filter field store a string like: {"field1": "value1", "field2": "value2"}. Then, somewhere in code: filters = MyModelFilter.objects.filter(owner_id=owner_id) querysets = [MyModel.objects.filter(**json.loads(filter)) for filter in filters] result_queryset = reduce(lambda x, y: x|y, querysets) This is not safe and I need to control available filter keys somehow. On the other hand, it presents full power of django queryset filters. For example, with this code I can filter related models. So I wonder, is there any better approach to this problem, or maybe a 3rd-party library, that implements same functionality?