Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Able to makemigrations and migrate locally but not on Heroku
There seems to be a problem with migrating my models on the Heroku server. I am able to run python manage.py makemigrations and python manage.py migrate just fine and I am able to view my site on my local machine (SQLite), but when I try to run migrations on Heroku (PostgreSQL) I get the following error: remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute remote: return self.cursor.execute(sql, params) remote: psycopg2.errors.UndefinedTable: relation "portfolio_category" does not exist remote: LINE 1: ...ategory"."name", "portfolio_category"."name" FROM "portfolio... remote: ^ remote: remote: remote: The above exception was the direct cause of the following exception: remote: remote: Traceback (most recent call last): remote: File "/app/manage.py", line 22, in <module> remote: main() remote: File "/app/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped remote: res = handle_func(*args, **kwargs) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 75, in handle remote: self.check(databases=[database]) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check remote: all_issues = checks.run_checks( … -
Django test field that slug is created from
I'm trying to write a test for UpdateView of Model which has a title and slug. When I try to test my view I can't recive a response because save method throws an ERROR Reverse for 'books-delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<slug>[^/]+)$'] I understand that slug can not be empty and that's what I try to test. So step by step: MODEL from django.utils.text import slugify class Book(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(max_length=120, unique=True, blank=True) def __str__(self) -> str: return f'{self.title}' def save(self, *args, **kwargs): self.slug = slugify(self.title) return super().save(*args, **kwargs) TEST class BookUpdateTest(TestCase): def test_book_must_have_title(self): """Create book object and updates fields with wrong data""" book = Book.objects.create(title='Camera Work 2') response = self.client.post( reverse('books-update', kwargs={'slug': book.slug}), {'title': '',}) self.assertEqual(response.status_code, 200) How the test for title field should look like? -
Distribution of Django based application [closed]
I want to distribute a Django based application to run on customer's intranet. I want to give a simple way to install the application, one script or tgz to install everything needed, including a http server and a database. What is the right way to do that? -
dynamically update html content and get the file content as a string in Django rest framework
I am doing the back-end side of a web application using Django rest-framework and PostgreSQL as database. I have an html file. I need to change some field values of the html based on the data getting from front-end and need to pass the html contend to another API as a sting. Please help me to find a proper solution. -
How to use async Django views without sleep?
I'm working on a Django view where I have two time-consuming operations that could be run in parallel (reads from a remote DB). I have created an async view but, presumably because I have no sleep statements, my code is still executing sequentially. If I understand correctly, Python code will always be executed sequentially until it finds some statement that allows it to pause and go execute the other task. I understand that sleep is one of these statements, but what are the others? The documentation and every single tutorial I found uses sleep statements in literally ALL of their examples. It almost seems like the only way to make code run async is to use a sleep statement, but that seems weird because sleep makes my code pause and do nothing, which can't be suitable for production. Here's some code that runs asynchronously: import time import asyncio from django.http import HttpResponse async def func1(n): print("Running func1...") for i in range(n): await asyncio.sleep(1) print("Done with func1!") return n async def func2(n): print("Running func2...") for i in range(n): await asyncio.sleep(1) print("Done with func2!") return n async def myview(request): print("Running myview...") start = time.time() res1, res2 = await asyncio.gather(func1(3), func2(4)) duration = … -
Django group by foreign key and return its object
I need some help with django orm. I have an EvaluationScore model and a Category Model class EvaluationScore(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) score = models.FloatField(null=True) category = models.ForeignKey('Category', on_delete=models.CASCADE, db_column='id_category') class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=100) What I want to do is to query EvaluationScore and return the average by category. So I did something like this EvaluationScore.objects.values('category').annotate(Avg('score')) The problem is that it returns a dict like this for every gategory {'category': UUID('67a56798-24da-4800-af15-79b9839a3f84'), 'score__avg': 28.166666666666668} What I need is the category object, not only the UUID. Is there a way to do so? -
Show only "Reorder" item
I am using Django and in the front end, I am trying to show only "Reorder" Parts on the table. To define the status of Available and Reorder, I am normally using the if-else method to track. I was thinking about filtering but I have no such Status field in my DB. Anyone can give me any idea how to do that? Here is what I've done for now HTML <tr> <th class="serial">#</th> <th>Part No</th> <th>Part Name</th> <th>Quantity</th> <th>Status</th> <th>Date</th> <th>Action</th> </tr> {% if parts %} {% for part in parts %} <tr> <td class="serial">{{ forloop.counter }}</td> <td>{{ part.partno }}</td> <td>{{ part.partname }}</td> <td>{{ part.quan }}</td> <td> {% if part.quan <= part.limit %} <p style="color: #FF0000"> Reorder </p> {% elif part.quan > part.limit %} <p style="color:#008000"> Available </p> {% endif %} </td> <td>{{ part.created_date }}</td> </tr> Part Table -
Django: Create objects from list of inequal dicts
Is there a way to call MODEL.objects.create() and map values from a list of dicts with inequal keys? Usually, I would write some IF statements but that might result in a lot of most the same code. Example code: accounts = [ {'name': 'A', 'age': 18, 'food': 'pizza'}, {'name': 'B', 'age': 20, 'shoe': 'adidas'}, ] for a in accounts: Account.objects.create( name=a['name'], age=a['age'], food=a['food'], # SET ONLY IF IN DICT OTHERWISE TAKE DEFAULT shoe=a['shoe'] # SET ONLY IF IN DICT OTHERWISE TAKE DEFAULT ) -
How to use Light Select2Widget instead of ModelSelect2Widget for foreign key with django-select2
In my django app I have a CenterModel with a CenterType field (foreigm key). I am using django-select2 ModelSelect2Widget to represent CenterType in the form. With ModelSelect2Widget the data is NOT pre-rendered onto the page, So i have to start typing in the search box before I would be able to see the CenterTypes names in the select2 widget. Since there are not too many Center types is there any way to pre-render all the options onto the page so I can see the widget like this image As you can see all the options are available from the begining. I dont need to type anything to see the options I want the widget for Center type to look that way class CenterModel(models.Model): name = models.CharField(verbose_name=_("Nombre"), max_length=50, unique=True,blank=False, null=False) center_type_id = models.ForeignKey("CenterTypeModel", verbose_name=_("Tipo"), blank=True, null=True, on_delete=models.SET_NULL, related_name="centers") class CenterTypeModel(models.Model): name = models.CharField(verbose_name=_("Nombre"),unique=True, max_length=50, blank=False, null=False) description = models.TextField( verbose_name=_("Descripción"),max_length=500, blank=True, null=True) #TODO saber si esto debe ser unico def __str__(self): return self.name from django_select2.forms import ModelSelect2Widget class CenterForm(forms.ModelForm): class Meta: model = CenterModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'center_type_id' : ModelSelect2Widget(model=CenterTypeModel, queryset=CenterTypeModel.objects.filter(), search_fields=['name__icontains'], attrs={'style': 'width: 100%;'}), -
Is there a way we can create Django JWT access token and refresh token by using our own auth models (no inbuilt user model), from inside the views?
I want to authenticate the user to a third party website and then only issue a token. So I need to create both the access token and the refresh tokens manually from the views, without using any inbuilt user models. How to do that? -
Write properly appointment system with availabilities
My aim is to create an appointment system in Django able to create appointment between teachers and student with the possibility for teachers to choose their availabilities and for student to choose time slots according to teacher's availabilities. There are 2 classes : One is the class with the teacher's availabilities: the foreign key is the teacher and there are also the date and the start time and end time One is the class appointment with 2 foreign keys for both student and teacher But now how to withdraw an time slot availability in the teacher's class availabilities to not allow student to ask an appointment at the same time ? -
How do i change size of runcatewords_html in django template?
I have used truncatewords_html|90 for the truncate paragraphs. I want to change the size of truncatewords_html to 50 in mobile mode. How do I do it? {{ student.description|safe|truncatewords_html:90 }} in desktop mode {{ student.description|safe|truncatewords_html:90 }} in mobile mode -
django-auditlog not working for User model
I am using django-auditlog for creating entries in LogEntry table. my actions for User Model are not getting logged in LogEntry table. my User model - class User(AbstractUser): ... ... ... username = None USERNAME_FIELD = 'id' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return f"{self.email}" ... ... auditlog.register(User) *I have to use django-auditlog only so pls suggest accordigly TIA -
React rendered components from Django doesn't show after reloading
I have a Django project that emits Javascript(ReactJS) to the browser as frontend. It's an SSR app -- Django renders a view with a template that loads a React script. Everything works just fine except when I go to a different page(React component routed with React-router) and reload the browser. The Django server routes the URL to a pattern that doesn't exist in URLconf, hence the interference with react components that result in a Django 404 error. Is there a workaround to solve this? PS: I chose this method rather than the decoupled method for compatibility and testing purposes. Below are the essential parts that relate the issue: Backend urls.py from django.urls import path from frontend import views urlpatterns = [ path("", views.react_template, name="react_template"), ] views.py from django.shortcuts import render def react_template(request): return render(request, "template.html", {"title": "Chatter"}) template from django.urls import path from frontend import views urlpatterns = [ path("", views.react_template, name="react_template"), ] Frontend App.js import React, { useEffect, Fragment } from "react"; import ReactDOM from "react-dom"; import webSocketInstance from "../utils/websocket"; import PrivateRoute from "../utils/privateRoute"; // ... import Chat from "./chat/chat"; import CreateRoom from "./chat/room"; import { BrowserRouter, Switch, Route, Link } from "react-router-dom"; export default function App() { return … -
how to save all item of cart in model order single field instead of creating creating ever item other field
i want to fetch all the item in a single model field instead of creating spreat field for every item my models.py class Order(models.Model): status_choices = ( (1, 'PENDING'), (2, 'CONFIRMED'), (3, 'PACKED'), (4, 'SHIPPED'), (5, 'IN WAY'), (6, 'ARRIVED DESTINATION'), (7, 'RECIEVED'), (8, 'COMPLETED') ) payment_status_choices = ( (1, 'SUCCESS'), (2, 'FAILURE' ), (3, 'PENDING'), ) user = models.ForeignKey(User, on_delete=models.CASCADE,) item = models.ForeignKey(Item, on_delete=models.CASCADE ) status = models.IntegerField(choices = status_choices, default=1) method = models.CharField(max_length=50, blank=False,) size = models.CharField(max_length=20, blank=False) price = models.FloatField(blank=False) created_at = models.DateField(auto_now=True, editable=False) payment_status = models.IntegerField(choices = payment_status_choices, default=3) order_id = models.CharField(unique=True, max_length=200, null=True, blank=True, default=None) datetime_of_payment = models.DateTimeField(default=timezone.now) def placeorder(self): self.save() def __str__(self): return self.user.username my views.py for saving the form not using modelform class Checkout(View): def post (self, request,): user = request.user address = Address.objects.filter(user=request.user, default=True) cart = request.session.get('cart') items = Item.get_items_by_id(list(cart.keys())) prefer = request.POST.get('payment') for item in items: order = Order(user=user, item=items, method=prefer, size=cart.get(str(item.id)), price=item.price) order.save() request.session['cart'] = {} return redirect('transactions:cart',) what i want to save all the product id which are in cart and in single field after clicking checkout and his total price in place of price and its all size in place of size but right now it does creating … -
How can I only change the fields attribute in inherited serializer class in DRF?
I have a serializer as:- class SuperUserListSerializer(serializers.Modelserializer): class Meta: model = User fields = ( 'id', 'username', 'email', 'password', 'first_name', 'last_name', 'phone_number', 'birth_date', 'is_active', 'is_staff', 'is_superuser', 'groups', ) I want to remove some of the fields from this serializers, so what I did, rewrote the Meta class and gave the serializer appropriate required fields:- class UserListSerializer(SuperUserListSerializer): class Meta: model = User fields = ( 'id', 'username', 'email', 'password', 'first_name', 'last_name', 'phone_number', 'birth_date', 'is_active', 'groups', ) I am not satisfied by this approach, Is there any way I can do, so that I am not required to re-introduce the Meta class, and pass/change the appropriate fields for the second serializer -
In javascript Event source response error occurs while publish data
I am trying to publish some data.Js throws this error. EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection. -
Django-REST-Framework validate fails: "this field is required"
some context here... I have a Room object that has a list of pictures. Right now I'm stuck at the POST method (create a new room with pictures). But I keep getting the validation error "this field is required". model class Room(models.Model): CONDO = 'condo' HOUSE = 'house' OTHER = 'other' ROOM_TYPES = [(CONDO, 'condo'), (HOUSE, 'house'), (OTHER, 'other')] name = models.CharField(max_length=50) price = models.IntegerField() type = models.CharField(max_length=5, choices=ROOM_TYPES) location = models.CharField(max_length=100) info = models.TextField(max_length=500, blank=True) owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='listings', null=True) start_date = models.DateField() end_date = models.DateField() is_available = models.BooleanField(default=True) include_utility = models.BooleanField(default=False) allow_pet = models.BooleanField(default=False) include_parking = models.BooleanField(default=False) include_furniture = models.BooleanField(default=False) class RoomPicture(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='images', null=True) image = models.ImageField(upload_to='images/', blank=True, null=True) class Meta: unique_together = ['room', 'image'] serializer class RoomPictureSerializer(serializers.ModelSerializer): class Meta: model = RoomPicture fields =['id','image'] class RoomSerializer(serializers.ModelSerializer): # images = serializers.ImageField(upload_to='images/', blank=True, null=True) images = RoomPictureSerializer(many=True) class Meta: model = Room fields = ['id', 'owner', 'name', 'price', 'type', 'location', 'info', 'start_date', 'end_date', 'is_available' , 'include_utility' ,'allow_pet', 'include_parking', 'include_furniture', 'images'] def create(self, validated_data): images_data = validated_data.pop('images') room = Room.objects.create(**validated_data) for image_data in images_data: RoomPicture.objects.create(room=room, image=image_data["image"]) return room views def convert(image): dict = {} # dict['id'] = 0 dict['image'] = image return dict class RoomViewSet(viewsets.ModelViewSet): … -
Html conditional rendering good practice in django?
I want to show an empty page design if there isnt any data from admin. I know it can be achieved using {% empty %} or if condition on template. But, please let me know if the below code is good to go ? In my views.py, if books.exists(): return render(request, 'index.html') else: return render(request, 'nobook.html') Is the above a good practice or should i try with {% if not books %} render this... {%else %} render this ... {% endif %} Please guide on which to use and which is a good practice ? -
Email in Django not sending
Good day, I have a Django app which I'm trying to send an email with Gmail SMTP, all my email settings are correct so is my views.py file but the email doesn't send and I receive no exceptions. I'm confused. pls, help. thanks. I'm pulling my values from an HTML form. -
How to get model name of m2m field
My question here is how to get the table name which each m2m field is related to like that : class Table1(models.Model): ... class Table2(models.Model): table1 = models.ManyToManyField(Table1) get m2m fields of model many_to_many_fields = [field for field in model._meta.many_to_many] so what i want here to get the name of model for table1 field which is Table1 -
Javascript does not work in Django templates with foundation 6
I have these scripts loaded to my template <script src="{% static 'js/jQuery.min.js' %}"></script> <script src="{% static 'js/app.js' %}"></script> <script src="{% static 'js/plugins/foundation.core.js' %}"></script> <script src="{% static 'js/plugins/foundation.reveal.js' %}"></script> <script src="{% static 'js/plugins/foundation.util.touch.js' %}"></script> <script src="{% static 'js/plugins/foundation.util.triggers.js' %}"></script> <script src="{% static 'js/plugins/foundation.util.mediaQuery.js' %}"></script> <script src="{% static 'js/plugins/foundation.util.motion.js' %}"></script> <script src="{% static 'js/plugins/foundation.util.box.js' %}"></script> <script src="{% static 'js/plugins/foundation.util.keyboard.js' %}"></script> Anyways, my Foundation modals do not work. When I click the button made for this purpose, it doesn not do anything. The repo if you want to test it: https://github.com/RodrigEEz/PersonalBlog -
Foreign key usage?
To all the pros out there. I finally figure out the issue i am having and I have read the foreign key posts in the past but none answer the question i have. My knowledge of foreign key is to link 2 tables while 1 of the table has a pre stored input so the foreign key takes the pre stored input to link to the 2nd table. Now my question comes: Is there a way to use foreign key on new data? Such as using django form with 2 models. Lets say I have this page which is to add a totally new device (None of the 2 tables have any info on this new device). And when i key in the forms. I want to allow saving of the 1st model then pass on (lets say 1st model have the field of 'hostname' and 'ipaddr') 'hostname' to the 2nd table as foreign key so the rest of the fields( model 2) within the same form get saved. Is this possible? I have my existing codes but it is not doing the above at all. It is currently registering the new device to a pre stored device at the … -
Pyhton os.listdir cannot find folder on hosting
So i am using Django and this code faces = {} for f in os.listdir('faces'): if 'png' in f: faces[f.split('.')[0]] = cv2.cvtColor(cv2.imread(str('faces/' + f), 0), cv2.COLOR_BGR2RGB) doesn't work. Django says it can't find this folder. Why? How can i scan folder on my hosting? -
Django register view fails, save is 'force_insert'
The error I get is: TypeError at /register/ save() got an unexpected keyword argument 'force_insert'