Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Merge equal fields in returned response independent of amount of objects Django Rest Framework
How can i merge equal fields and append different values to the fields in the returned response into one, independent of the amount of objects? When accessing the enpoint, i currently get the following response: [ { "colors": [ "Red", "Orange", ], "styles": [ "Rock" ], "application": [ "Wall" ], "material": [ "Mosaic" ] }, { "colors": [ "Yellow", ], "styles": [ "Mosaic" ], "application": [ "Wall" ], "material": [ "Ceramic" ] } ] While want to achieve something like the snippet bellow, where unique values are appended and equal fields are merged: [ { "colors": [ "Red", "Orange", "Yellow" ], "styles": [ "Rock" "Mosaic" ], "application": [ "Wall" ], "material": [ "Mosaic" "Ceramic" ] }, ] My serializer is structured like this: class ProductFiltersByCategorySerializer(serializers.ModelSerializer): """ A serializer to display available filters for a product lust """ colors = serializers.StringRelatedField(read_only=True, many=True) styles = serializers.StringRelatedField(read_only=True, many=True) application = serializers.StringRelatedField(read_only=True, many=True) material = serializers.StringRelatedField(read_only=True, many=True) class Meta: model = Product fields = ( 'colors', 'styles', 'application', 'material' ) My viewset is structured like this: class ProductFiltersByCategory(generics.ListAPIView): """ This viewset takes the category parameter from the url and returns related product filters """ serializer_class = ProductFiltersByCategorySerializer def get_queryset(self): category = self.kwargs['category'] return Product.objects.filter(category__parent__name__iexact=category).distinct() … -
rendering the correct width with css
I'll add some pics, to make everything clear.. this is how it should look and it looks like that but when the screen's width is less than 580px it looks as follows i'll share my html ans css and what i have tried.. my html: <div class="d-flex item"> <div class="image" style="background-image: url({{meal.image.url}});" data-aos="fade"> </div> <div class="text"> <a href="{% url 'meals:meal_detail' meal.slug %}"><h3>{{meal.name}}</h3></a> <p>{{ meal.description|truncatewords:15 }}</p> <p class="price">${{meal.price}}</p> </div> </div> <!-- .item --> if you don't use django forget that sintax used just imagine it's some random text, cz it is. my css: .bg-image, .half .image, .image-bg-fullwidth { background-size: cover; background-position: center center; background-repeat: no-repeat; background-attachment: scroll; } .half .text, .half .image { width: 100%; } @media (min-width: 992px) { .half .text, .half .image, .m { width: 50%; } } .half .text { padding: 7%; background: #000; } .half .text h2 { color: #fff; } @media (max-width: 991px) { .half .image { height: 250px; } } .image-bg-fullwidth { display: block; height: 300px; } .menus .item .image, .menus .item .text { width: 50%; } .menus .item .image { background-size: cover; background-position: center center; } .menus .item .text { padding: 40px; background: #000; } .menus .item .text h3 { color: #fff; font-size: 22px; … -
How to override user.save() method
I only want to override the save() method of the built-in User model. Is it possible to do it without creating a new model? -
How to add spaces between lines and align elements in the same column in InlineCheckboxes of crispy-form (Django)?
I have a form field which is CheckboxSelectMultiple and I use InlineCheckboxes from crispy-forms to make all those check boxes inline. Since I don't have the image of it I will use code snippet as an example. this is how I want the form looks like in html and I will use stars instead of boxes *name1 *name2 *name3 *name4 *name5 *name6 *name7 *name8 *name9 *name10 *name11 *name13 What can I do to add more spaces between each line and make it aligns vertically like shown above? here is my forms.py class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = ['student',] widgets = {'student': forms.CheckboxSelectMultiple()} def __init__(self, class_pk, current_user, *args, **kwargs): super(AttendanceForm, self).__init__(*args, **kwargs) current_student = Class.objects.get(id=class_pk) self.helper = FormHelper(self) self.fields['student'].queryset = current_student.student.order_by('first_name') self.helper.layout = Layout( InlineCheckboxes('student') ) my current html. (it's not aligned perfectly as shown below!) <form method="POST" class="ml-auto mr-auto"> {% csrf_token %} <div style="text-align: justify;">{% crispy form form.helper %}</div> <button type="submit" class="btn btn-success btn-sm" style="font-size: 15px" > Check </button> </form> Thanks before hand! -
Django model works on local but not after deploy
I am making a simple personal website. I make a box to input user data (name, email, and message). I want this data is sent to my django admin. I have test it and it works in local. But when i deploy it, i didn't get any data whenever i submit from the box. Note : i do not use django form for some reason. I want to use my own custom form. this is my views.py from django.shortcuts import render from django.http import HttpResponse from .models import Feedback from .forms import FeedbackForm def index(request): if (request.method == "POST"): name = request.POST.get("Name") email = request.POST.get("Email") message = request.POST.get("Message") record = Feedback(name=name, email=email, message=message) record.save() return render(request, 'main.html') this is my models.py from django.db import models class Feedback(models.Model) : name = models.CharField(max_length=50) email = models.EmailField() message = models.CharField(max_length=200) def __str__(self): return self.name -
Django OneToOneField on_delete CASCADE convention
I have these models in my code class Address(models.Model): street = models.CharField(max_length=50) city = models.CharField(max_length=10) class User(models.Model): name = models.CharField(max_length=20) age = models.IntegerField() address = models.OneToOneField(Address, on_delete=models.CASCADE) I understand how models.CASCADE works in Django. If I delete an Address record, the corresponding User record would be deleted, but this is not what I want. I want the Address record to be deleted if the User record gets deleted. I know I can accomplish that by putting the OneToOneField in Address rather than User, but that doesn't make sense to me from a database schema perspective because a User has an Address. An Address doesn't have a User. I tried searching about how to force the deletion to go in the reverse way, but apparently it's not possible from all the options that Django has (https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.ForeignKey.on_delete). Does anyone know an alternative? Or the right way to construct the database schema otherwise? Thank you! -
Django multivaluedictkeyerror in imagefield
My views.py file: My edit_blog view when i submit my edit form without editing fields it will return multivaluedictkeyerror why? My edit_blog.html file: This my html file. It includes styles, Layout and edit part of my blog with values. @csrf_exempt def edit_blog(request, id): if request.method == 'POST': title = request.POST['title'] author = request.POST['author'] description = request.POST['description'] image = request.FILES['image'] fs = FileSystemStorage() filename = fs.save(image.name,image) uploaded_file_url = fs.url(filename) updated_blog = Blog.objects.filter(id=id).update(title = title, author = author, description = description, image = image) messages.success(request, f'Blog Updated Successfully') return redirect('blog') elif request.user.id: myblog = Blog.objects.get(id=id) return render(request, 'edit_blog.html',{'myblog': myblog, 'id': id}) My edit_blog.html file: This my html file. It includes styles, Layout and edit part of my blog with values. {% extends 'layout.html' %} {% block body %} <!DOCTYPE html> <html> <link rel="stylesheet" href="/static/signupstyle.css"> <head> <title>Edit Blog</title> </head> <body> <h1>Edit Blog</h1> <form id="myform" autocomplete="off" method="POST" enctype="multipart/form-data" action=""> {% csrf_token %} <div class="floating-form"> <div class="floating-label"> <input type="text" name="title" value="{{myblog.title}}" class="floating-input" placeholder=" " maxlength="50" id="id_title"> <span class="highlight"></span> </div> <div class="floating-label"> <input type="text" name="author" value="{{myblog.author}}" class="floating-input" placeholder=" " maxlength="50" id="id_author"> <span class="highlight"></span> </div> <div class="floating-label"> <textarea name="description" cols="40" rows="10" class="floating-input floating-textarea" placeholder=" " maxlength="100000000" id="id_description">{{myblog.description}}</textarea> <span class="highlight"></span> </div> <img class="img-circle" src="{{ myblog.image.url }}" width="200" height="200"> … -
Pagination with filtered queryset in ListView
I have a heir of ListView which looks like that: class Index(ListView): model = Recipe paginate_by = 9 def get_template_names(self): if self.request.user.is_authenticated: return 'index_authenticated.html' return 'index_anonymous.html' def get_tags(self): return Tag.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tags'] = self.get_tags() return context def get_queryset(self): if self.request.GET.getlist('filters'): qs = self.model.objects.filter(tags__name__in=self.request.GET.getlist('filters')).distinct() if qs: return qs return self.model.objects.all() return self.model.objects.all() Removing any filter parameter will result in queryset getting shorter hence returning an error: Invalid page (2): That page contains no results Is there any way to handle such things beside creating custom pagination? -
Django - loop through items in model textfield
I got a app which should show the news. Every topic is saved with a different URL but all crated in the same model: class Module(models.Model): namee = models.CharField(max_length=120, null=True, blank=True) css = models.TextField(max_length=50000, null=True, blank=True, default='<style> </style>') content = models.TextField(max_length=50000, null=True, blank=True, default='DEFAULT') javascript = models.TextField(max_length=50000, null=True, blank=True, default='<script> </script>') I prepared my views.py to fetch the data from the api like this: def edit(request): import requests import json news_api = requests.get('https://newsapi.org/v2/everything&apiKey=my_api_key') api = json.loads(news_api.content) modules_all = Module.objects.all() return render(request, 'main/index2.html', { 'newsapi': api, 'modules_all': modules_all, } Inside my template I render the data from the content field (Module model) to display the html code. I used {% for data in newsapi.articles %} {{ data.title }} {% endfor %} in the content field and {{ module_all.get.content|safe }} in the template. Unfortunately the for loop is not rendered. If I paste the loop straight into the html template (without query from database Module.content) it works fine. Does someone have an explanation why this is happening and how I can fix? -
Invalid block tag , expected 'endblock' while trying to sort an object_list
Hi I'm trying to sort a list by vote count but my template doesn't accept it. I'm new to Django so probably did it completely wrong. {% extends "base.html"%} {% block title %}Leaderboard{% endblock title %} {% block content %} <table style="width:99%"> <td>LEADERBOARD<td> <tr><td>-</td></tr> {% newlist = sorted(object_list, key=lambda x: x.votes, reverse=True) %} {% for entry in newlist %} <tr> <td> {{entry.artist}} - <ahref="#TODO">{{ entry.name }}</a></td><td>Votes: {{ entry.votes }}</td> </tr> {% endfor %} </table> {% endblock content %} -
Can't push local Postgre database to Heroku
i have a problem getting my local database into Heroku.I'm currently working on building a Django web application and I tried to learn about getting local database to Heroku .I was trying to push my local Postgresql database with pg:push command then this error happen pg_restore: error: unrecognized data block type (0) while searching archive ! pg_restore errored with 1 Any idea why is this happened ? -
Customizing model fields in a form
Django version is 3.1, Python version is 3.7 I have a question regarding customization of model field options when displaying it in a form for the user to use. I've got a model that has got a lot of fields where you need to specify a level. The levels need to be stored in the database as numbers from 1 to 3, for easier filtrating (when someone wants to filter an object that has not exact level of 2, but let's say 2 and above) so it can't be a string value. Since there's a lot of those level fields, I've decided that it would be useful to use Choices. models.py class Cat(models.Model): LOW = 0 NORMAL = 1 HIGH = 2 VERY_HIGH = 3 LEVEL_CHOICES = ( (LOW, 'Low'), (MEDIUM, 'Medium'), (HIGH, 'High'), (VERY_HIGH, 'Very high'), ) first_attribute_level = models.IntegerField(choices=LEVEL_CHOICES, default=LOW) second_attribute_level = models.IntegerField(choices=LEVEL_CHOICES, default=LOW) third_attribute_level = models.IntegerField(choices=LEVEL_CHOICES, default=LOW) fourth_attribute_level = models.IntegerField(choices=LEVEL_CHOICES, default=LOW) Now, when I desplay this model as a form on my view where the user may add a Cat instance (not in Admin) the obvious and expected behaviour is a select list with options LOW, MEDIUM, HIGH, VERY HIGH. What I would want to happen, is … -
Django how to get distinct objects into ManyToMany field?
I have a problem, I need to get all the distinct ingredients into my ManyToMany field. I found a few questions like this on StackOverflow but I didn't found how to implement this into a ManyToMany field, so I hope that you can help me. Here is what I got: ingredients = models.ManyToManyField(Ingredients.objects.all().distinct()) This throws the error: [...] First parameter to ManyToManyField must be either a model, a model name, or the string 'self' I know why it comes but I don't know how to solve it. Thank you for your help! -
How to upload multiple images Using django?
I have Following Code in my models.py class MyModel(models.Model): my_images= models.ImageField(upload_to='image/') My forms.py is class MyForm(forms.ModelForm): class Meta: model = MyModel fields = "__all__" and in my Views.py file is having following code def myfunction(request): if request.method=='POST': form = MyForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponse('Data Inserted') else: return HttpResponse('form is invalid') this Code is inserting single image into Database and directory.i want to Add multiple images into my directory and database. here i am making API so i am sending formdata(image) from postman app.how to Upload multiple images? -
How to use a django abstract class with graphene-django?
I'm trying to have a unique interface for two concrete classes that are similar and inherit from a common abstract class. My django model classes: class Metadata(models.Model): name = models.CharField(max_length=255) sequence = models.PositiveSmallIntegerField() is_choices = False class Meta: abstract = True class MetadataScalar(Metadata): string_format = models.CharField(max_length=255, blank=True, null=True) class MetadataChoices(Metadata): is_choices = True choices = models.CharField(max_length=255, blank=True, null=True) My graphene-django api: class MetadataNode(DjangoObjectType): class Meta: interfaces = (Node,) connection_class = Connection model = Metadata fields = '__all__' class MetadataScalarNode(MetadataNode): class Meta: interfaces = (Node,) connection_class = Connection model = MetadataScalar fields = '__all__' class MetadataChoicesNode(MetadataNode): class Meta: interfaces = (Node,) connection_class = Connection model = MetadataChoices fields = '__all__' class CreateMetadata(ClientIDMutation): metadata = Field(MetadataNode) class Input: name = String(max_length=255, required=True) sequence = Int(required=True) string_format = String() choices = List(String) @classmethod def mutate_and_get_payload(cls, root, info, **input): if 'string_format' in input: metadata = MetadataScalar.objects.create( name=input.get('name'), sequence=input.get('sequence'), string_format=input.get('string_format') ) elif 'choices' in input: metadata = MetadataChoices.objects.create( name=input.get('name'), sequence=input.get('sequence'), choices=','.join(input.get('choices')) ) return CreateMetadata(metadata=metadata) When querying the graphql mutation corresponding to CreateMetadata, the metadata concrete class is successfully created. ;-) The problem is that when the query asks for the created concrete Metadata in the result (here either MetadataScalar or MetadataChoices), graphql cannot find a … -
How can I get active users in Django?
I need to know which users are active using Django to mark them with a green circle, I searched a lot but I could not find any solution to this problem -
Why can't I specify a file location from media folder with pandas in django?
I'm trying to get pandas to read a file from the media folder as read_excel(). This is what I've tried: from django.shortcuts import render from .models import Benchmark import pandas as pd # Create your views here. def main_view(request): file = pd.read_excel('media/uploads/benchmarks/benchmarks_for_website', index_col=0) context = { 'df': file.to_html() } return render(request, 'main.html', context) It compiles, but when I try to access the html page in the browser this is the error that appears: FileNotFoundError at /benchmarks/ [Errno 2] No such file or directory: 'media/uploads/benchmarks/benchmarks_for_website.xlsx' What am I doing wrong? Also, I have the MEDIA_ROOT and MEDIA_URL: MEDIA_URL = '/media/' MEDIA_ROOT = '/home/user/project/media' Any help is very much appreciated! -
Django CMS Contact Form
Does Django CMS have a contact form plugin which when submitted will send an e-mail to both my e-mail and the submitter's e-mail? I plan to have a downloadable form where the field only contains the submitter's name and e-mail then the submitter will receive an e-mail with an attached pdf -
django restframwork and simple_jwt and login test
I have a problem to test the login with simple jwt and django rest framework: This is what i have: def create_user_registration_data(): return { 'username': 'username', 'email': 'email@www.com', 'password': 'password12345' } class UserViewSetTest(TestCase): def setUp(self): self.registration_data = create_user_registration_data() def test_login_user(self): self.user = create_user_model(self.registration_data) my_user = User.objects.get(username=self.registration_data['username']) self.factory = APIRequestFactory() self.login_data = {'username': self.registration_data['username'], 'password': self.registration_data['password']} request = self.factory.post('/api/token/', data=self.login_data,format='json') view = csrf_exempt( MyTokenObtainPairView.as_view()) response = view(request) The model is actually created and the user is active, however when trying to call the viewset view i get the response Unauthorized {'detail': ErrorDetail(string='No active account found with the given credentials', code='no_active_account')} What am i doing wrong here, the user is definitely created. -
I am facing OperationalError at /admin/login/ no such table: auth_user problem
I am new in Django. firstly I create a project then app.and this app name initialized in my project setting.py file. then migrate, after migrate I create a superuser. but when I log in it's shows error and the error message is "OperationalError at /admin/login/ no such table: auth_user" Traceback is https://dpaste.com/322NH9YKX.txt How can I fix this, Thank you -
Django - CreateView doesn't save
I have two type of objects in my model - 'users' and 'groups' . I successfully made "create" page for "users" with help of CreateView, but for some reason when I am doing very same with "groups" - it doesn't save. No errors, it simply doesn't create new entry in database after I push submit button. Here is my views.py from django.shortcuts import render # Create your views here. from .models import User, Group from .forms import UserForm, user_form, group_form from django.shortcuts import get_list_or_404, get_object_or_404, redirect from django.views.generic import UpdateView, CreateView, DetailView, ListView, UpdateView, DeleteView class user_create(CreateView): template_name = "user_create.html" form_class = user_form success_url = '/users' class group_create(CreateView): template_name = "group_create.html" form_class = group_form success_url = '/groups' My models.py: from django.db import models from django.conf import settings # Create your models here. class Group(models.Model): #ID, Name, Description, Actions groupname = models.CharField(max_length=20) description = models.TextField(max_length=200, blank=True, null=True) #To make in name, not objXXX def __str__(self): return self.groupname class User(models.Model): #username, created, group, actions username = models.CharField(max_length=20) date_joined = models.DateField(auto_now=False, auto_now_add=True) group = models.ForeignKey(Group, on_delete=models.PROTECT, blank=True, null=True) #To make in name, not objXXX def __str__(self): return self.username Forms used for templates: from django import forms from django.db import models from .models import … -
Django manytomany field shows model name and id via model form, but not the attributes
I have a manytomany in my model class A(models.Model): name = models.CharField(max_length=250) class B(models.Model): a = models.ManyToManyField('A') and a model form: class BForm(forms.ModelForm): class Meta: model = B fields = ['a'] labels = {'a': 'A'} I would now like to represent the Manytomany field via the model form: {% for field in BForm %} {{ field }} {% endfor %} It works with every field, the problem is that the manytomany field shows as values: A(1) A(2) A(3) A(4) A(5) A(6) ... I would like to have the names from the model there -
Django admin bootstrap theme not working in django admin
I am deploying two apps to Heroku .I have deployed one using bootstrap theme .The first app I deployed is using Django admin bootstrap theme and it works perfectly but I don't see my bootstrap theme is working in the second app and it does not have any styles. When I ran the second app locally I don't see that my bootstrap theme is working and I did everything perfectly written in the description on PyPi but I don't see anything changed in my admin can anyone help. my settings.py: Django settings for project project. Generated by 'django-admin startproject' using Django 3.0.7. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'zout1(cwz@w+8t__(sh3f+w-uxd9hjph@oq!-y87ea^y_sgn=i' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Retail_Management', 'bootstrap_admin' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Error Encountered During Oscar INstallation
I am trying to setup django-oscar using [this][1] guide, however [1]: https://django-oscar.readthedocs.io/en/2.0.4/internals/getting_started.html on running python manage.py migrate I got the following error: LookupError: No installed app with label 'communication' please how can I solve this? -
Why I am Unable To Add Likes To Article Modal- Django?
I am Using Django And I Have A Modal Called Article And For Like I Am Using A ManyToManyFeild In Django For Making A Like System, But I am Unable To Add Likes To My Article, I Can't Figure Out What Is Wrong Can Anyone Help, I Am Messing Around With Scripts But I See No Change... Here Is How My Likes Variable Look In Article Modal likes = models.ManyToManyField(User, related_name = 'likes') Here Is How My Like View @login_required(login_url='/accounts/login') def like_button(request, slug): article = get_object_or_404(Article, slug =request.POST.get('article_slug')) article.likes.add(request.user) return HttpResponseRedirect(reverse('detail', args=[str(slug)])) And This Is How My url Look Like path('like/<slug:slug>/', views.like_button, name='like_post'), And This Is How My Like I Represent My Like View On Front-End <form action="{% url 'like_post' article.slug %}" method="post"> {% csrf_token %} <button type="submit" class="btn btn-outline-primary" name="article_slug" value="article.slug" >Like</button> </form>