Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Select the book with the least amount of pages for each author in a category
These are my models: class Author(models.Model): name = models.CharField() class Category(models.Model): name = models.CharField() class Book(models.Model): pages = IntegerField() author = ForeignKey(Author) category = ForeignKey(Category) How do I select a book per author with the least amount of pages in a specific category? And then order by number of pages If there are two books with the same amount of pages, select any of those. If a author doesn't have books in a category, that author can be ignored. Thanks -
Features of html page does not work with django
I have made a html website with Adobe Dreamweaver. It was fine. I wanted to use it with django so I copied the folders, made template and static folder and everything. Most of the things work fine but there are some problems. I have no idea that where I can find the error. This is the worng version in my browser with django. This is the right version in my browser with dreamweaver. As you can see the navbar is smaller because the page is scrolled down and the section what I am looking is highlighted. <!DOCTYPE html> <html lang="en"> {% load staticfiles %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="FutureCode"> <title>FutureCode</title> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <!-- Plugin CSS --> <link href="{% static 'vendor/magnific-popup/magnific-popup.css' %}" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="{% static 'css/freelancer.min.css' %}" rel="stylesheet"> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg bg-secondary fixed-top text-uppercase" id="mainNav"> <div class="container"> <p><a class="navbar-brand js-scroll-trigger" href="#page-top">Future Code</a></p> <button class="navbar-toggler navbar-toggler-right text-uppercase … -
How to add a ListField in djongo models?
I want to add a ListField in my models using djongo models. Using Djongo's ListField is throwing an error while trying to update the fields from the admin site. keyword = models.TextField() domains = models.ListField() crawl_date = models.DateTimeField(auto_now_add=True, auto_now=False) class Meta: db_table = 'keywords' -
Django Invalid HTTP_HOST header Elastic Beanstalk
I'm running a large hobby site on AWS ELB. I've tried to resolve this problem searching StackOverflow but nothing quite works. I updated my settings.py and ALLOWED_HOSTS as follows: ALLOWED_HOSTS = ['127.0.0.1','.amazonaws.com','mysite.com','.elasticbeanstalk.com','localhost',] import requests EC2_PRIVATE_IP = None try: EC2_PRIVATE_IP = requests.get("http://169.254.169.254/latest/meta-data/local-ipv4", timeout = 0.50).text except requests.exceptions.RequestException: pass if EC2_PRIVATE_IP: ALLOWED_HOSTS.append(EC2_PRIVATE_IP) The ELB Health Check DOES work. However, I'm still getting thousands of error emails daily. For example: Invalid HTTP_HOST header: '54.84.163.167'. You may need to add '54.84.163.167' to ALLOWED_HOSTS. Report at / Invalid HTTP_HOST header: '54.84.163.167'. You may need to add '54.84.163.167' to ALLOWED_HOSTS. My site architecture is Cloudfront, to ELB, to Django. From what I can tell the IP address shown (and it does change regularly) is part of Amazons network. I suspect it is the load balancer itself but I don't know a way to confirm that and identify the load balancer ip address to add to allowed hosts. Any other thoughts or ideas? -
send list value from django template to the django view
I have a code written which dynamically add a list when the user clicks on the add button. for eg two lists are created- <ul> <li>samsung galaxy</li> <li>xiaomi redmi note 5</li> </ul> now I want to send the li data as a list ['samsung galaxy', 'xiaomi redmi note 5'] to the view when the user clicks on the compare button as. please help me to achieve this. -
how to automatically add another field to model if a boleanField is true?
I have a post model that has featured Boolean field. I want a field appears on admin panel if that Boolean is true. for example: if a post is featured user can add specific featured image if it's not true there is no field to show in panel for that item class Post(models.Model): is_featured = models.BooleanField(blank=False, default=False) if is_featured == True: featured_image = models.ImageField(upload_to='article_featured/') -
AttributeError at /admin/login/ Manager isn't available; 'auth.User' has been swapped for 'users.CustomUser'
I editing default user model to customize to add custom filed in my admin user module in django I was fallow below step: step1: Create new app called users step2:In users app model.py file add below code from django.contrib.auth.models import BaseUserManager,AbstractBaseUser from django.db import models class MyUserManager(BaseUserManager): def create_user(self,email,dob,password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), dob = dob, ) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, email, dob, password): user = self.create_user( email, password=password, dob=dob, ) user.is_admin = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): # add additional fields in here email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) phone = models.CharField(max_length=555) age = models.CharField(max_length=555) dob = models.DateField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['dob'] def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): # __unicode__ on Python 2 return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: … -
json response view function (Python) related undefind error
undefined error is occurred. An error occurred when defining edit_url as <% = edit_url%> code is below view code if request.is_ajax(): return JsonResponse({ 'author': comment.author.username, 'text':comment.text, 'created_at':comment.created_at, 'edit_url': comment.text, # 'delete_id':comment.id, }) template code <script class="reply_template" type="text/x-template"> <tr> <td><%= author %></td> <td> <%= text %> </td> <td><%= created_at %></td> <td> <a href="" class="btn btn-sm btn-info float-right"><%= edit_url %></a> <a href="" class="btn btn-sm btn-warning float-right">delete</a> </td> </tr> </script> -
How to convert a Django model instance to JSON using existing Tastypie Resource?
This problem is related to this other problem, but instead, I wish to convert a single model instance to JSON, using an existing Tastypie Resource. -
using Handler404 in django url dispatcher cause server error
I followed this https://stackoverflow.com/a/31381075/10087274 because I want when url does not exist a json shows error but the problem is here that I get server error 500 when I add handler404 in my url dispatcher here is my project url : from django.urls import path, include from django.conf.urls import handler404 from api.exception import custom404 handler404 = custom404 urlpatterns = [ path('api/v1/', include('acl.urls')), ] and I have exception.py inside my project folder (near settings.py) contains this: from django.http import JsonResponse def custom404(request): return JsonResponse({ 'status_code': 404, 'error': 'The resource was not found' }) I dont know how can I solve my problem -
Ajax posting succesful but Django receiving as Null value
Ajax sent data successful but Django function receiving it as Null Value.... tried all possible ways for days now yet same result....Please this is delaying me from submission date. have tried trying to send in json format but it rejects it $.ajax({ type: "GET", url: "results/", data: {'datum': 1000}, success: function(data){ console.log(data); alert("You will now be redirected."); window.location.href = "results/"; }, error: function(request, status, error, data){ console.log(error); }, }); Django view function thistry(request): if request.method == 'GET': dat = request.GET.get('datum') dee = 9 return render(request, 'studentapp/rough2.html', {'dat': dat, 'dee':dee}) django url path('weekly/teachers/results/', views.thistry, name='first_page_weekly'), -
putting commenting form on the same page as the post in django
I need help putting the commenting form for users on the same page as the post, currently i have the commenting form on another page but i'd really like the users to be able to post comments as soon as they are done reading the post, attached below is my template for the post ` <section class="main"> <div class="container"> <div class="row"> <section class="posts-wrapper col-sm-12 col-md-8"> <div class="posts"> <p class="movie-details"><a href="" class="date">{{articles.postdate}}</a> | {% for a in articles.category.all %}<a href="{{a.get_absoulte_url}}" class="genre">{{a}}, </a>{% endfor %} </p> <p class="movie-details pt-0"><b>Staring : </b> {% for c in articles.star.all %}<a href="{{c.get_absoulte_url}}" class="genre">{{c}}, </a>{% endfor %}</p> <p class="movie-details pt-0"><b>Directors : </b> {% for d in articles.director.all %}<a href="{{d.get_absoulte_url}}" class="genre">{{d}}, </a>{% endfor %}</p> <h3 class="title my-3">{{articles.title}}</h3> <p><b>Released:</b> {{articles.releasedate}}</p> <p><b>Seen:</b> {{articles.dateseen}}</p> <p class="text">{{articles.body | safe}}</p> </div><hr> <div class="comments-wrapper"> <h2 class="mt-5"><a href="{% url 'add_comment' slug=articles.slug %}">Leave a Comment</a></h2> <p>Total number of comments <span class="text-danger">{{articles.comments.count}}</span></p> <form action="" method="POST"> <button type="submit">Submit</button> <div class="form-row"> <div class="form-group col-md-6"> <input type="text" class="form-control" placeholder="username"> </div> <div class="form-group col-md-6"> <input type="email" class="form-control" placeholder="Email"> </div> </div> <div class="form-group"> <textarea name="" class="form-control" id="" rows="10"></textarea> </div> </form> <hr> <h2 class="mb-4">COMMENTS</h2> {% for comment in articles.comments.all %} <div class="comments py-2 my-3"> <div class="comments-img-wrapper"> <img src="" class="comment-image" alt=""> </div> <div class="comments-details"> … -
SQLite production deployment checklist for django and djangocms
I am going to deploy a djangocms website using sqlite db. My current db settings in settings.py: DATABASES = { 'default': { 'CONN_MAX_AGE': 300, 'ENGINE': 'django.db.backends.sqlite3', 'HOST': 'localhost', 'NAME': 'project.db', 'PASSWORD': '', 'PORT': '', 'USER': '' }} I've run through django deployment checklist (https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/) and reviewed notes related to sqlite (https://docs.djangoproject.com/en/1.11/ref/databases/#sqlite-notes). Looked through these docs as well: https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-DATABASES I've found no specific security-related notes except for the general requirement to keep db password safe (https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/#databases). I wasn't asked to provide db admin login and password during installation (djangocms installer didn't prompt for that). Do I need to worry about this? Is it kept safe? Are there any other sqlite-specific points to the deployment checklist I need to worry about? Thanks! -
Redirecting after Ajax 'POST'
I have a code of adding products list. when the user clicked the button a function is called which send the products list to the views by using ajax function submition(container){ $.ajax({ url :'/compare_in/', type : "POST", data : { com_list : container, csrfmiddlewaretoken: '{{ csrf_token }}' }, success : function() { console.log('success') }, error : function() { console.log('Failure'); } }); } now in the views code, the product's list value is manipulating and scraping the data by the list value and storing the data in the dictionary def compare_in(request): if request.method == 'POST': compare_res = request.POST.getlist('com_list[]') for item in range(len(compare_res)): if re.compile('edmi').search(compare_res[item]): compare_res[item] = 'xiaomi ' + compare_res[item] phone_list = ','.join(e.lower() for e in compare_res) phone_list = '-'.join(phone_list.split()) . . . return HTTPResponse() now I want to redirect to the different page with the value of the dictionary. Note-return render() is not working -
Product items is not iterable from models
I want to show all my objects that are in my models to the page that i have created all the code is given below, thanks models.py---->> from django.db import models from django.utils import timezone class Product(models.Model): title = models.CharField(max_length = 250) description = models.TextField(blank = False) price = models.IntegerField() datecreated = models.TimeField() featured = models.BooleanField(default = False) def __str__(self): return self.title def get_Absolute_url(self): return reverse("products", kwargs = {"id":self.id}) views.py---->> def home(request): obj = Product.objects.get() context = { "obj":obj } return render(request, "firstapp/home.html", context) templates---->> <h1>Products in database</h1> {% for x in obj %} <p>{{x.title}}</p> {% endfor %} getting error model objects are not iterable -
How to save selected data based on the id in Django
I am a newbie. I want to update the data (food_status) from my database based on the id (OrderId) and save it to food_status column. But, it shows an error TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' models.py class OrderItem(models.Model): Table_No = models.IntegerField(blank=False) FoodId = models.TextField() Item = models.TextField() Qty = models.IntegerField(blank=False) Price = models.TextField() Note = models.TextField(max_length=100, null=True) OrderId = models.TextField(max_length=100, null=True) FoodStatus = ( ('1', 'Has been ordered'), ('2', 'cooked'), ('3', 'ready to be served'), ('4', 'done'), ) food_status = models.CharField(max_length=50, choices=FoodStatus, default="has been ordered") views.py def kitchen_view(request): chef_view = OrderItem.objects.all() if request.method == "POST": status = OrderItem.objects.filter(id= ['OrderId']).update(food_status=['food_status']) food_status = request.POST.get("food_status") status.food_status = food_status status.save(update_fields=['food_status']) return render(request, 'restaurants/kitchen_page.html', {'chef_view':chef_view}) kitchen_page.html <form action="#" method="post"> {% csrf_token %} {% for order in chef_view %} <table width="800"> <tr> <th width="800">Table Number</th> <th width="800">Item</th> <th width="800">Quantity</th> <th width="800">Price</th> <th width="800">Note</th> <th width="800">Order Id</th> <th width="800">Status</th> </tr> <tr> <td width="800">{{ order.Table_No }}</td> <td width="800">{{ order.Item }}</td> <td width="800">{{ order.Qty }}</td> <td width="800">{{ order.Price }}</td> <td width="800">{{ order.Note }}</td> <td width="800">{{ order.OrderId }}</td> <td width="800">{{ order.Status }} <input type="text" name="food_status" placeholder="food_status" required=""/> </tr> </table> {% endfor %} <a href='' button onclick="myFunction()"><input type="submit" value="Change Status"></button> </form> … -
Pycharm lost connection between views and template
One day I discovered that one Django application lost the connection between views and a template. I checked the whole project and this problem got only one application. There is no connection in views between the function and the template. There is no code highlighting in the template, and the template does not recognize tags, for example: {% url%}, <script src="{% static '...'%}"> </ script>, {% extends "base.html"%} and so on. The application is correctly written in INSTALLED_APPS, does have a namespace in the urls and works correctly in the browser if the project is launched. The only one thing have changed: I recently had updated PyCharm to: (PyCharm 2019.1.2 (Professional Edition) Build #PY-191.7141.48, built on May 7, 2019) -
How should I change the path in "urlpatterns"?
I am trying to create a blog, and want that articles were devided by categories. Version of Django:2.1, Python:3.7 I don't understand how should I change the path in the urlpatterns for displaying the name of category, not . Where can I check examples of the Django code? I tried to do path('category.title') but it doesn't work. This is my models.py: from django.db import models from django.conf import settings from django.urls import reverse class Category(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='', blank=True) def __str__(self): return self.title class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) image = models.ImageField(upload_to='', blank=True) cat = models.ForeignKey( Category, on_delete=models.CASCADE, null=True, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments') comment = models.CharField(max_length=100) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.comment def get_absolute_url(self): return reverse('article_list') This is urls.py: from django.urls import path from . import views from .models import Category urlpatterns = [ path('', views.ArticleViewList.as_view(), name='article_list'), path('<int:pk>/edit/', views.ArticleUpdateView.as_view(), name='article_edit'), path('<int:pk>/delete/', views.ArticleDeleteView.as_view(), name='article_delete'), path('<int:pk>', views.ArticleDetailView.as_view(), name='article_detail'), path('new/', views.ArticleCreateView.as_view(), name='article_new'), ] This is class-based view for returning the list of articles: class ArticleViewList(LoginRequiredMixin, ListView): model = models.Article template_name = 'article_list.html' … -
django has created problem page not found when i use dynamic url
app/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name = "home"), url(r'^productform/', views.product_create_view, name="productform"), url(r'^products/<int:id>', views.products, name="products"), ] root/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('firstapp.urls')), ] views.py--->> def products(request, id): obj = Product.objects.get(id=id) context = { "objects":obj } return render(request, "firstapp/products.html", context) getting page not found error i am getting this error on my browser enter image description here -
Limit choise in django form by foreign key relations
My model class MacroPianoDeiConti(models.Model): codice = models.CharField(max_length=6) descrizione = models.CharField(max_length=400) class PianoDeiConti(models.Model): macro = models.ForeignKey(MacroPianoDeiConti, on_delete=models.SET_NULL, null=True, blank=True, default=None, related_name='MacroP') codice = models.CharField(max_length=6) descrizione = models.CharField(max_length=400) tipo = models.ForeignKey(ContoTipo, on_delete=models.SET_NULL, null=True, blank=True, default=None, related_name='ContTi') def __str__(self): return str(self.codice) + ' ' + self.descrizione class CostoDocumento(models.Model): dataregistrazione = models.DateField(default=date.today()) numerodocumento = models.CharField(max_length=6) datadocumento = models.DateField(default=date.today()) fornitore = models.ForeignKey(Fornitori, on_delete=models.SET_NULL, null=True, blank=False, default=None, related_name='Forn') importo = models.FloatField(null=True, blank=False, default='0') conto = models.ForeignKey(PianoDeiConti, on_delete=models.SET_NULL, null=True, blank=False, default=None, related_name='Cont') inizio = models.DateField(null = True, blank = True, default = None) fine = models.DateField(null=True, blank=True, default=None) def __str__(self): return self.dataregistrazione + ' ' + self.fornitore ''' And this is my form: ''' class CostoDocumentoForm(forms.ModelForm): class Meta: model = CostoDocumento fields = '__all__' labels = { 'dataregistrazione': _('Data Registrazione'), 'numerodocumento': _('Numero Documento'), 'datadocumento': _('Data Documento'), 'fornitore': _('Fornitore'), 'importo': _('Importo'), 'conto': _('Conto'), 'inizio': _('Inizio Periodo'), 'fine': _('Fine Periodo'), } def __init__(self, *args, **kwargs): super(CostoDocumentoForm, self).__init__(*args, **kwargs) self.fields['conto__macro_id'].queryset = self.fields['conto__macro_id'].queryset.filter(conto__macro=1) ''' I want to filter cascade fields in template by conto__macro=1 TY -
How to write API for Signup in Django
I am trying to write API for signup. But its adding data to admin but i want to store my data to MySQL database. Help me to write code for that. serializers.py class SignupSerializer(serializers.ModelSerializer): class Meta: model = Signup fields = ('username', 'phone_number', 'email', 'password', 'address' ) views.py class SignupAPIView(APIView): def get(self, request): signup = Signup.objects.all() print(signup) serializer = SignupSerializer(signup, many=True) print(serializer) return Response(serializer.data, status=200) def post(self, request): data = request.data print((data)) serializer = SignupSerializer(data=data) print(serializer) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.error, status=400) When i POST data it is adding in Admin file not to MySQL database. I want to add this POST data to MySQL database. -
Is there a way to hide part of a URL created from the Wagtail admin page tree?
Let's say I've created a blog for my website. The tree structure setup in the Wagtail admin looks like this: Homepage > Blog Index > Blog Post Is it possible to keep the Blog Index page in the admin page tree but remove it from the URL so that my URL's look like this: Homepage > Blog Post I am assigning a custom group to the Blog Index page which allows them to edit only Blog Posts that they have created, which is why Blog Index needs to stay in the tree on the admin side. I've done a little work with the routablepagemixin but not to eliminate anything from the URL, only add to it. -
Formset in Django Classbased CreateView
Model class Timetable(models.Model): day = models.CharField(max_length=9,choices=timetable_choices) start = models.IntegerField() end = models.IntegerField() period = models.CharField(max_length=12) Views class Timetableadding(CreateView): model = Timetable fields = ['day','period','start' ,'end'] success_url = '/dashboard' What I need is to process a view similar to following image , Is it possible with formset in CBV-Creatview or shall I need to do this using functional createview ? -
urls setting in django in root directory
i am trying to find out my mistake but i am unable to recognise, give me the better syntax thanks root/urls.py----> from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('firstapp.urls')), ] app directory/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name = "home"), url(r'^productform/>', views.product_create_view, name = "productform"), url(r'^products/<int:page_id/>', views.products, name = "products"), ] i have done with my settings.py in root -
Mysql query taking too much time to fetch data in python
I am fetching data from 3 tables which is giving around 30000 rows . When I run this query using phpmyadmin it takes around 45 seconds to execute. Due to this query my website is getting slow . Can anyone tell me how to make this query much fast? Query SELECT cd.data1,cd.data2_name, cv.item1_name,cv.item2,cv.items3, sd.date FROM table1 as cd LEFT JOIN table2 as cv ON cv.demo_id = cd.id LEFT JOIN table3 as sd ON sd.test_id = cd.id WHERE cd.temp= 5 GROUP BY cd.id order by cd.time DESC Note : I am using this query in python django website .