Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' -
Primary Key(count) for each user - Django
I have a Django website and part of it lists data in rows with the primary key in one of the columns. This works great except for when I have separate users. I'm using foreign keys in each model to separate the different user's data. My problem is that the data for each user has to have a number in the column that increments numerically and does not have any spacing, for instance, 1,2,3,5 is bad. If User1 is uploading data and halfway through User2 uploads a row of data then if I use the primary key the numbers will not be in numerical order for each user and will read 1,2,3,5 for User1 and 4 for User2. I tried forloop counter but I need the numbers all the be assigned to the row and not change if one is deleted. Ive been at this for 2 weeks and am having a really hard time describing my problem. I think I need somesort of Custom User Primary Key, a primary key for each user. Any help at this point is greatly appreciated, Thanks! -
When I click clear button: The 'image' attribute has no file associated with it
I create a user update page for my site. I added 'change image' section. It is works but when I click the "CLEAR" button I take this error: ValueError at /user/update The 'image' attribute has no file associated with it. I want when I click the "clear" button delete old image and assign default.jpg to new image. ----OR---- How do I delete or hide "Clear" button in my site My Models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to ="profile_pics", null=True,blank=True) def __str__(self): return f"{self.user.username} Profile" def save(self, *args, **kwargs): super().save(*args, **kwargs) # super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) My forms: class UserUpdateForm(forms.ModelForm): email = forms.EmailField username = forms.CharField class Meta: model = User fields = ["username", "email"] widgets = { "username": forms.TextInput(attrs={"class": "form-control "}), "email": forms.TextInput(attrs={"class": "form-control "}), } class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ["image"] My signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() my Views: def update_profile(request): if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request.user) U_username = request.POST['username'] U_email = request.POST['email'] p_form = ProfileUpdateForm( request.POST, request.FILES, instance=request.user.profile) userName = … -
How to use a model with multiple other models
This is probably pretty simple but I am having a mental block so help is appreciated. I have a discussion app which contains a Message model. I want to relate the Message to several other models (e.g. Video, Note, etc.). I don't feel that it is right to add a field for each model onto the Message model but I want the messages to "cascade delete" when the parent object is deleted (e.g. if Video is deleted so all related Message's should be deleted as well). How can I accomplish this? class Message(models.Model): """ Stores information pertaining to a message. """ sender = models.ForeignKey( Employee, on_delete=models.CASCADE, null=True, related_name='messages' ) message = models.TextField() parent = models.ForeignKey( 'self', related_name='children', null=True, blank=True, on_delete=models.SET_NULL ) created_on = models.DateTimeField(auto_now_add=True) # this seems wrong # video = models.FK # note = models.FK # etc... -
How to store dark mode choice with Javascript in Django?
This post is hidden. You deleted this post last month. I have the following script NioApp.ModeSwitch = function() { var toggle = $('.dark-switch'); if($body.hasClass('dark-mode')){ toggle.addClass('active'); }else { toggle.removeClass('active'); } toggle.on('click', function(e){ e.preventDefault(); $(this).toggleClass('active'); $body.toggleClass('dark-mode'); }) } Which changes the website to dark-mode, through this toogle <li><a class="dark-switch" href="#"><em class="icon ni ni-moon"></em><span>Dark Mode</span></a></li> How can I, in Django, store this with Javascript, so that it remembers the user option? -
Running a py file as a script Django
I have created a Django app which I have uploaded to PythonAnywhere. I want to use the below code to run as a separate task, which basically runs through all of the bookings in the system and sends an email if the booking has passed today's date. I previously had this in the Views.py file and the code works fine when the page refreshes but I basically want it to be run separate each morning at a particular time. The issue I am having if I try to run the py file even locallly "py completed_bookings.py" it does not recognise any of the imports. Examples include "ModuleNotFoundError: No module named 'sendgrid'" and "ImportError: attempted relative import with no known parent package" I think this may be down to the structure or the way I am trying to run it but unsure how this is suppose to be done. Currently this file is sitting with the rest of my app files. Thanks in advance for any help. Below is the py file I created in the app to be run separate. from datetime import datetime, timedelta import datetime from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail from twilio.rest import Client import … -
Getting 'No changes detected in learning_log' in new Django project
I'm new to python and django, and I'm following a tutorial from the Python Crash Course book 2nd edition, for creating a simple website. This is my first time using django. I am simply following along with the book, but I have run into a roadblock with the error 'No changes detected in learning_log'. I'm using django 2.2 for this project if that makes any difference. Here are my installed apps in settings.py INSTALLED_APPS = [ # My Apps 'learning_logs', # Default Apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Here is the DATABASES code in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # I had to change this from 'NAME': BASE_DIR / 'db.sqlite3' 'NAME': str(BASE_DIR / 'db.sqlite3'), } } Note: I changed 'NAME': BASE_DIR / 'db.sqlite3' to 'NAME': str(BASE_DIR / 'db.sqlite3') to address a previous error: 'TypeError: argument of type 'WindowsPath' is not iterable' To migrate the database I used python manage.py makemigrations learning_logs (ll_env) PS C:\Users\Admin\documents\scripts\pythondir\learning_log> python manage.py > makemigrations learning_logs this resolved the TypeError, but is still giving me the message 'No changes detected in app 'learning_logs''. I used verbosity to give me more details and it gave me this information (ll_env) PS C:\Users\Admin\documents\scripts\pythondir\learning_log> python manage.py … -
¿como puedo tener todas sus Reservas? foreing key django
Como puedo obtener los datos relacionados de mi foreignkey y al llenar mi formulario, tengo mi modelo class Service(models.Model): branch = models.ForeignKey(Endpoint, verbose_name="Sucursal", on_delete=models.CASCADE) pr = models.CharField(max_length=50, null=True, blank=True, verbose_name="prueba") lo que quiero es que al seleccionar la relacion que trae "branch", me llene en el otro campo en este caso "pr" ponga los otros datos que trae esa relacion de "branch". -
Django : Related Field got invalid lookup: user
I want to find practice data based on the user primary key. So when I open the url: localhost:8080/api/practice-filter?user=1 it will output all practice data based on the user with id 1. model.py class Practice(models.Model): practice_id = models.BigAutoField(primary_key=True) user = models.ForeignKey('User', models.DO_NOTHING, default=None) score = models.SmallIntegerField(null=True) class Meta: managed = True db_table = 'practice' def __str__(self): return str(self.practice_id) class User(models.Model): user_id = models.BigAutoField(primary_key=True) fullname = models.CharField(max_length=50) email = models.CharField(max_length=100) password = models.TextField() class Meta: managed = True db_table = 'user' def __str__(self): return self.fullname view.py @api_view(['GET']) def practice_filter(request): if request.method == 'GET': exercises = Practice.objects.all() user = request.GET.get('user', None) if user is not None: practice_filtered = exercises.filter(user__user__icontains=user) exercises_serializer = PracticeSerializer(practice_filtered, many=True) return JsonResponse(exercises_serializer.data, safe=False) But when i run the above code i get an error : Related Field got invalid lookup: user How to solve this error? I do not know what to do. I'm still a beginner and need a lot of guidance. Please help. Thank you. -
How to render multiple outputs from a function triggered by an html form in Django
Ive been creating a website that essentially replaces financial analysts. I've been adding projects that calculate various statistics and models, however I cant figure out how to have multiple outputs (organized in different containers) for one request returned on the page. Clarification (2 parts): For example, I have one section that is a financial statement builder. The input from the HTML form is a ticker, the view takes the request, calls the statement builder function and returns the statements as an html table, so I can render it in one location. Now, another section is a fundamental financial statistics calculator. It takes in the ticker for the form input which is used as the parameter for the function, however it calculates about 25 different ratios and metrics. I want to organize these on a data dashboard (everything else is built) , however am not sure how to organize multiple outputs in different locations from one request. Thank you for any help! -
Django tinymce htmlfield being displayed as textfield in production
I have a tinymce htmlfield on mysite, and while testing it on localhost it displays as normal, but when i commit it to my site and access its admin, the field is displayed as if it was a textfield here it is in localhost and here it is in production here's what the console on my site shows settings.py INSTALLED_APPS = [ 'grappelli', 'filebrowser', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tinymce', -
no such table: users_user
I need to create POST method Registration Form i have this code (i am using django rest_framework): Users.models class User(AbstractBaseUser): username = models.CharField(max_length=20, unique=True) email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELD = 'username' class MyUserManager(CreateAPIView): def post(request, *args, **kwargs): username = request.data.get('username') email = request.data.get('email') password = request.data.get('password') user = model(username=username, email=normalize_email(email)) user.set_password(password) return user users.serializers: class MyUserManagerSerializers(serializers.ModelSerializer): username = serializers.CharField(max_length=20) email = serializers.EmailField() password = serializers.CharField() class Meta: model = models.User fields = ['email', 'username', 'password'] and models.views.py: class UserManagerAPIView(ListCreateAPIView): serializer_class = MyUserManagerSerializers def UserRegistration(request): user = UserManager.post(request) serializers = MyUserManagerSerializers(user) serializers.is_valid(raise_exception=True) serializers.save() return Response(serializer.data, status=status.HTTP_201_CREATED) urls.py urlpatterns = [ path('register', UserManagerAPIView.as_view()), and installed_apps: INSTALLED_APPS = ['users.apps.UsersConfig'] AUTH_USER_MODEL = 'users.User' when i am send POST method to localhost:8000/register i always get error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) The above exception (no such table: users_user) was the direct cause of the following exception: File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, … -
How can I append data from html to array in views from a button?
I'm trying to build a website that generates a power hour style video from a list of music videos that the user selects by searching through the youtube api. I'm having trouble figuring out how to append selected videos to a list (addedVideos) in view.py from a button (add) in my html. I need to append each added video to a list so I can display them and loop through them in an embedded youtube player. This is my first django project so I don't have a good understanding of what the potential problems could be. index.html and views.py below: views.py import requests from isodate import parse_duration from django.conf import settings from django.shortcuts import render, redirect def index(request): addedVideos = [] videos = [] if request.method == 'POST': search_url = 'https://www.googleapis.com/youtube/v3/search' video_url = 'https://www.googleapis.com/youtube/v3/videos' search_params = { 'part' : 'snippet', 'q' : request.POST['search'], 'key' : settings.YOUTUBE_DATA_API_KEY, 'maxResults' : 3, 'type' : 'video' } #print(request.POST['submit']) r = requests.get(search_url, params=search_params) #print(r) results = r.json()['items'] #print(results) video_ids = [] for result in results: video_ids.append(result['id']['videoId']) if request.POST['submit'] == 'lucky': return redirect(f'https://www.youtube.com/watch?v={ video_ids[0] }') video_params = { 'key' : settings.YOUTUBE_DATA_API_KEY, 'part' : 'snippet,contentDetails', 'id' : ','.join(video_ids), 'maxResults' : 3 } r = requests.get(video_url, params=video_params) results … -
S3 Lambda Trigger not triggering for EVERY file upload
In Python Django, I save multiple video files. Save 1: Long Video Short Video Save 2: Long Video Short Video Save 3: Long Video Short Video I have a lambda trigger that uses media converter to add HLS formats to these videos as well as generate thumbnails. These 3 saves are done in very short time periods between each other since they are assets to a Social Media Post object. For some reason the S3 triggers for only some of the files. Save 1 triggers S3 Lambda but not Save 2. Save 3 also triggers S3 Lambda. My assumption is that the S3 trigger has some sort of downtime in between identifying new file uploads (In which case, I think the period in between these file uploads are near instant). Is this assumption correct and how can I circumvent it? -
Django link form to fields to model
Im abit confused on how to link form fields to the model field. I wanted to create a radio button that yes stands for "defect" and no for "No Defect. So in the form i created the following: CHOICES = [('Defect', 'yes'), ('No Defect', 'no')] self.fields['Audit_outcome'].widget = forms.ChoiceField(choices=CHOICES) But when i do that i get the following error: 'ChoiceField' object has no attribute 'attrs' -
How to pass string to content of meta tag for template?
{% if is_inner_page %} <meta name="description" content={{ description }}> {% else %} <meta name="description" content="Text sample"/> {% endif %} When i passed string to template with render in view, I get only first word of string in content, so how to pass full string of description to template? If i pass not in content, then all is ok, please help me :( -
How to implement tinymce with django for client side?
I did lot of research on how to implement django tinymce for users and not for admin but I got no real answer. Is there any way to do it. Any help would be highly appreciated... -
Django not able to see data from the model on web page
I am trying to build a project management system but I am not able to see the data from the models on the web page. My code is below. Also, I am not sure if the data is getting stored in the database at all. models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class CustomUser(AbstractUser): user_type_data = ((1, "Admin"), (2, "Staff"), (3, "Client")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class AdminUser(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Staffs(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) phone = models.CharField(max_length=15, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.contrib import messages from django.core.files.storage import FileSystemStorage #To upload Profile Picture from django.urls import reverse from django.views.decorators.csrf import csrf_exempt from django.core import serializers import json from powercons_app.models import CustomUser, AdminUser, Staffs, Projects, Tasks, Clients, Contracts from .forms import AddClientForm, EditClientForm def add_staff(request): return render(request, "admintemplate/add_staff_template.html") def add_staff_save(request): if request.method != "POST": messages.error(request, "Invalid Method ") return redirect('add_staff') else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') username = …