Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR in node_modules/stream-chat/dist/types/connection.d.ts
i follow this tutorial https://getstream.io/blog/realtime-chat-django-angular/ . I had been faced to an error while start the project by using npm-start command. I will show the error in below. enter image description here -
How to order messages based on the time its send like in normal chats?
Hey guys I am having trouble with ordering the messages based on the timestamp like in normal chats. How to do it? can anyone give me a proper solution? I have updated the question with the model manager I use. This is the model. class Chat(models.Model): first_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='first_user_chat', null=True) second_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='second_user_chat', null=True) timestamp = models.DateTimeField(auto_now_add=True) class ChatMessage(models.Model): chat = models.ForeignKey(Chat, blank=True, null=True, on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='sender', on_delete=models.CASCADE) message = models.TextField() # read = models.BooleanField(blank=False, null=True) timestamp = models.DateTimeField(auto_now_add=True) model manager class ChatManager(models.Manager): def by_user(self, user): qlookup = Q(first_user=user) | Q(second_user=user) qlookup2 = Q(first_user=user) & Q(second_user=user) qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct() return qs # method to grab the thread for the 2 users def get_or_new(self, user, other_username): # get_or_create username = user.username if username == other_username: return None, None # looks based off of either username qlookup1 = Q(first_user__username=username) & Q(second_user__username=other_username) qlookup2 = Q(first_user__username=other_username) & Q(second_user__username=username) qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct() if qs.count() == 1: return qs.first(), False elif qs.count() > 1: return qs.order_by('timestamp').first(), False else: Klass = user.__class__ try: user2 = Klass.objects.get(username=other_username) if user != user2: obj = self.model(first_user=user, second_user=user2) obj.save() return obj, True except Klass.DoesNotExist: user2 = None return None, False views class ChatView(LoginRequiredMixin, … -
Forbidden (CSRF token missing or incorrect.): /data
I am trying to post data to a URL using the requests library, code below. data = {"a": 1, "b": 2} cookies = {'csrftoken': django.middleware.csrf.get_token(request)} app_url = "http://localhost:8000/data" headers = {"app_key": key} r = requests.post(app_url, data=json.dumps(data), headers=headers, cookies=cookies) I am getting Forbidden (CSRF token missing or incorrect.): /data [11/Sep/2020 14:45:22] "POST /data HTTP/1.1" 403 2513 I used the django-cors-headers package also and allowed CORS_ALLOWED_ORIGINS = [ "http://localhost:8000" ] Still, the forbidden error is there. I can make the view csrf_exempt but I don't want to compromise on security. Is there any other way? -
Interaction of python and java usingpy4j during deployment
Recently I have been working on a project to make a RESTapi using Django rest_framework. This framework requires some processing and objects which need to be done in java. I came across this library called Py4J which allows us to access Java objects, collections etc from a python environment. What I could understand was that To make JVM accessible to python I had to interact with another server localhost:25333. I have written a very basic code to test: Views.py from py4j.java_gateway import JavaGateway class TestClass(APIView): permission_classes = [AllowAny] authentication_classes = [] @staticmethod def post(request): gateway = JavaGateway() fn = gateway.entry_point.getFunc() response = Response() response.data = {"res": fn.print()} return response Func.java public class Func{ public String print() { return "Hello from java"; } } TestGateway.java import py4j.GatewayServer; public class TestGateway { private Func func; public TestGateway() { func = new Func(); } public Stack getFunc() { return func; } public static void main(String[] args) { GatewayServer gatewayServer = new GatewayServer(new TestGateway()); gatewayServer.start(); System.out.println("Gateway Server Started"); } } This code works as expected since every interaction is happening on the localhost. But I need to deploy both the java application and django rest api on Google AppEngine. How will the two codes … -
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 …