Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How can I roll back or retrieve data in fields?
I have a question in Django. I changed the name of fields my models.py on my editor. After changing the name, I made makemigrations and did 'migrate' on cmd. After 'migrate', I checked my database on DB broswer and I found that not only the name of fields changed, but the data of the fields also changed into the name of fields I just changed as just lowercased. i.e.) Original name of field was ingredient and I changed the name to Essential_ingredient. I checked DB and turned out that all of data for the column of changed field is essential_field like picture. I posted this question on FB page and one said I can roll back by doing "migrate ". So I tried it and then it turned out that the field came back to original table but the data of the field hasn't changed back to original. Does any know any way solution like my situation? Thanks in advance. -
How to properly return Json reponse to template for ajax/jquery?
Here I am trying to search with the help of ajax and jquery with my django view. When I try to search like this by returning the JsonReponse instead of html_template it doesn't return data below the corresponding id in html But When I return html from django view and create the new html for this searching results and including this template in the original template works perfectly but I find this a longer process So I tried to return json reponse from view and use that json objects in the template like this but it is not working. How can I solve this ? I think I need to work on the ajax part . def search_users(request): q = request.GET.get('q') if q: users = get_user_model().objects.filter(is_active=True).filter(profile__full_name__icontains=q) data = {'users': users} else: users = get_user_model().objects.filter(is_active=True) data = {'users':users} return JsonResponse(data) ajax $(function() { $('#search_users').keyup(function() { $.ajax({ type: "GET", url: "{% url 'dashboard:search_users' %}", data: { 'q' : $('#search_users').val(), }, success: searchSuccess, dataType: 'json' }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search_users_results').json(data) #doing html instead of json works after returning html from django view } -
How to add ipv6 in allowed_hosts in django?
My allowed_hosts looks like below: ALLOWED_HOSTS = ['192.168.225.56','127.0.0.1,'[2409:4072:400:.....]'] Error ALLOWED_HOSTS = ['192.168.225.56','127.0.0.1,'[2409:4072:400:.....]'] SyntaxError: invalid syntax -
Getting the select form values for multiple obects in Django
I am making an attendance system for a school. I'm displaying the name and roll no. of the students in the form by retrieving the values from the database and a third option is a form dropdown to select the status of the student, i.e, Present or Absent. The problem is that if there are multiple students in the same class the attendance status of all the students are being saved as the same value as the first roll no. For ex: If roll 1 is present then all the students are marked present regardless of the options I've selected in the form element. Just need help with how to save the different status for individual student which I'm selecting. Views.py def attendance(request, pk): teacher = Teacher.objects.get(id = pk) classes = Class.objects.get(class_teacher = teacher) if request.method =="POST": if 'attend' in request.POST: request.session['date'] = request.POST.get('date') students = Student.objects.filter(classes = classes) return render(request, "dashboard/teacher_attendance.html", {"classes": classes, "students": students, "teacher": teacher}) elif 'mark' in request.POST: students = Student.objects.filter(classes = classes) date = request.session.get('date') for s in students: status = request.POST.get('status') a = Attendance() a.student = s a.classes = s.classes a.att_date = date print(status) a.attendance = status a.save() return redirect('teacher', teacher.id) else: return render(request, … -
Is there an analog of the command chmod +x in Windows
If not, how to run Python files globally as when working with Django (django-admin).Thank you in advance -
Django mail not working in case of signal only
TypeError at /admin/api/staff/4/change/ object of type 'Staff' has no len() Request Method: POST Request URL: http://127.0.0.1:8000/admin/api/staff/4/change/ Django Version: 2.2.11 Exception Type: TypeError Exception Value: object of type 'Staff' has no len() Exception Location: /usr/lib/python3.5/email/_parseaddr.py in getaddrlist, line 252 Python Executable: /home/fractaluser/Desktop/upwork/paul/env/bin/python Python Version: 3.5.2 Python Path: ['/home/fractaluser/Desktop/upwork/paul', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/fractaluser/Desktop/upwork/paul/env/lib/python3.5/site-packages'] Server time: Sun, 15 Mar 2020 05:39:20 +0000 @receiver(post_save, sender=Staff) def hear_signal(sender, instance , **kwargs): if kwargs["created"]: return # mail([instance], "name") return def mail(list, name): from smtplib import SMTP,SMTPAuthenticationError,SMTPException from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText host = "smtp.gmail.com" port = 587 username = "" password = "" from_email= username to_list=list try: email_conn = SMTP(host, port) email_conn.ehlo() email_conn.starttls() email_conn.login(username,password) the_msg = MIMEMultipart("alternative") the_msg['subject'] ="Sponsorshop approval" the_msg["from"]=from_email plain_txt = "testing the message" html_text = '<h1>Hello</h1>' part_1 = MIMEText(plain_txt,'plain') part_2 = MIMEText(html_text,"html") the_msg.attach(part_1) the_msg.attach(part_2) email_conn.sendmail(from_email,to_list,the_msg.as_string()) email_conn.quit() except SMTPException as sm: print(sm) Here is my code. I am trying to send a mail when my Staff models gets updates or created. The same mail is working fine incase of email verification in case of login or register. but, throwing error in the signal @receiver. Can't we send mail in @receiver method. Or is there any way to achive that ? … -
Displaying fields according what the user select in the previous fields in Django
I am new to django, I want to create fields that will be changed according to the user choice in the previous field i.e when user choose 2 in first field then 2 different fields will appear below to that first field. For example: if he chosed 2 in Number of subjects field then 2 different fields will appear stating Subject 1 Name and Subject 2 Name. Any help will be appreciated. Here is the front end of the page on how it will look like -
Django REST Framework the field was declared on serializer but not included
I think this is a relation issue between django default user and app. First of all, I have this project structure. foo_project - foo_project - __init__.py - asgi.py - settings.py - urls.py - wsgi.py - apps - board - __init__.py - admin.py - apps.py - models.py - serializers.py - tests.py - urls.py - views.py - accounts - __init__.py - admin.py - apps.py - models.py - serializers.py - tests.py - urls.py - views.py Board, # models.py class Board(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') title = models.CharField(blank=False, max_length=255) body = models.TextField(blank=False) image = models.ImageField(upload_to='time_line_photo') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Meta: ordering = ['-created'] # serializers.py from rest_framework import serializers from .models import Board from django.contrib.auth.models import User class BoardSerializer(serializers.ModelSerializer): class Meta: model = Board fields = ('id', 'author', 'title', 'body', 'image', 'created','updated') # views.py from django.contrib.auth.models import User from django.shortcuts import render from rest_framework import generics from .models import Board from .serializers import BoardSerializer class BoardList(generics.ListCreateAPIView): queryset = Board.objects.all() serializer_class = BoardSerializer class BoardDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Board.objects.all() serializer_class = BoardSerialize Accounts, # serializers.py from rest_framework import serializers from django.contrib.auth.models import User from ..board.models import Board class UserSerializer(serializers.ModelSerializer): board_field = serializers.PrimaryKeyRelatedField( many=True, … -
hex literal too big in sqlite
So I wanted to convert msyql query to sqlite where in it has images in hex code,when I run the same query in sqlite browser it is giving me an error, what is the correct way of doing it. Result: hex literal too big: 0x73616666726f6e2e6a7067 At line 1: INSERT INTO `test` (`id`, `yeild`, `image`, `city`, `info`, `fertilizer`) VALUES (9, 'Wheat', 0x77686561742e6a7067, 'Bangalore', 'Weather that is comfortable for humans is also good for wheat. Wheat needs 12\r\nto 15 inches (31 to 38 centimetres) of water to produce a') -
Django: Join two models
I have two models like this: class Author(AbstractUser): name = models.CharField(max_length=100) address = models.CharField(max_length=200) class Book(AbstractUser): name = models.CharField(max_length=100) author = models.ForeignKey(Author, related_name='book', on_delete=models.CASCADE) I want to query all authors who own at least 1 book (we can do it in sql easily). So i tried: Author.book.all() and got an error: ReverseManyToOneDescriptor' object has no attribute 'all' How can i do this with Django ORM? Please help me!! -
django admin site how to control fields width
this is what its looks like in my admin site How to minimize the space between the label and his selection box or field? for example the ESC label and the selection box this is my admin.py class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): list_display = ('lrn', 'Student_Users', 'Education_Levels', 'ESC', 'Courses','strands', 'Section', 'Payment_Type', 'Discount_Type' ,'School_Year','Date_Time') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') search_fields = ('Student_Users__Firstname','Student_Users__lrn','Student_Users__Lastname') fieldsets = ( ('Name of Applicant', { 'fields': ('Student_Users',) }), ('Student Information *', { 'fields': ('Student_Types',('Old_Student','New_Student'), 'School_Year', ('Education_Levels','ESC','Courses', 'strands'), ('Payment_Type', 'Discount_Type')) }), ) and this is my models.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True) Old_Student = models.BooleanField(null=True, blank=True) New_Student = models.BooleanField(null=True, blank=True) Date_Time = models.DateField(auto_now_add=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) strands = models.ForeignKey(strand, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) ESC = models.ForeignKey(esc, on_delete=models.CASCADE,null=True,blank=True) Student_Types = models.ForeignKey(student_type, related_name='+', on_delete=models.CASCADE, null=True,blank=True) -
If I need more custom functionality can I manually write HTML forms?
I started coding a couple years ago but it's all been in Python and I never learned HTML/CSS real in-depth. I've now got a decent grasp of Django and somewhat of how the data gets passed around Django but I've noticed some limitations to the functionality I am trying to achieve using Djangos forms module. I think it would help better if I understood the front-end better. This has got my attention so I started to try learning about front-end frameworks like react.js, as well as HTML/CSS/vanillaJS. Today I'm a couple hundred pages deep into an HTML book and finding out more about forms than I knew. I've always seen the forms from the Django side (other than a few manual HTML forms I write every now and then). So I guess my question is, and it might be stupid, can I simply render a function based or CBV for that matter and pass the context I need and do fully custom forms in the front-end? Then grab that data back in the view using request.GET? How to handle form validation like this? Is this one way of expanding the functionality of Django if I'm reaching limitations? I know it … -
Javascript and python real-time audio stream
i want to record audio in the client's browser and send it in real-time to server to process the audio stream in python. I found webRTC which is usefull for real-time but i can't find any example. What's the best solution ? Thank you! -
Django receive multiple files upload
<input type='file' name="images[]" /> files = request.FILES['images'] print(files[0].name) I have trouble to get multiple files upload in Django 3.0 Can anyone tell me why I got MultiValueDictKeyError -
Communicate with other Django Servers using Docker
I'm new to Docker and want to build a Django webapp. The app shall run on multiple computers with a central server, which basically run all the same image. The main point is that there will be computing tasks which I want to distribute over the servers. So now I wonder how I would communicate via Django between the different Servers. I know about basic Distributed styles and Architecture protocols, but how do I expose the local network to the docker image network layer, so that I can communicate on custom ports and IPs in my network? I read about Docker Swarm, but how to forward the Addresses to each Django Server? What is a best/recommended/efficient way to distribute tasks between my Django Apps with Docker? -
Django cannot create or render comments
Hi have this structure to handle users posts and comments my post model is from django.db import models from django.contrib.auth.models import User class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=0) profile = models.ForeignKey('users.Profiles', on_delete=models.CASCADE, null=True, default=1, blank=True) title = models.CharField(max_length=100, blank=True, null=True) desc = models.CharField(max_length=1000, blank=True, null=True) photo = models.ImageField(upload_to='posts/photos') created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return '{} by {}'.format(self.title ,self.user) and my comment model from django.db import models from posts.models import Post as Post from django.contrib.auth.models import User class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE, null=True, default=1, blank=True) name = models.CharField(max_length=20,blank=True, null=True) email = models.EmailField(max_length=20,blank=True, null=True) body = models.TextField(max_length=200,blank=True, null=True) created = models.DateTimeField(auto_now_add=True,blank=True, null=True) updated = models.DateTimeField(auto_now=True,blank=True, null=True) active = models.BooleanField(default=True,blank=True, null=True) class Meta: ordering = ('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post) im able to create post on admin from posts.models import Post as Post from django.contrib import admin from comments.models import Comment @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'post', 'created', 'active') list_filter = ('active', 'created', 'updated') search_fields = ('name', 'email', 'body') can create my post and persist on db now i have this function to persist the comment on front from django.shortcuts import render from .models import Post, Comment from .forms import EmailPostForm, CommentForm … -
Handling Django File from Model
I've created a basic model in Django and want to do some processing on a file in the background before sending to the template. At the moment I'm getting errors about a FileDescriptor object, which I cannot seem to find methods or attributes for, I was expecting something I can get a url or file contents from: class Projects(models.Model): image = models.ImageField(upload_to='uploads/') title = models.CharField(max_length = 200) desc = models.TextField() date_posted = models.DateTimeField() notebook = models.FileField(upload_to='notebooks/') I'd like to perform some processing on the file object in a generic view, but I don't really understand what is getting passed through. How can I just get the file url, or access to the actual contents of the file? Seem unable to get .url or .file attributes as I expect from FileField. class ProjectListView(ListView): model = Projects template_name = 'project_list.html' context_object_name = 'projects' def get_context_data(self, **kwargs): j = Projects.notebook.url context = super().get_context_data(**kwargs) ## insert functions to process object j ## context['notebook'] = j return context Thanks! -
How to add programmatically an image file to FileField from mezzanine.core.fields
I used Mezzanine==4.3.1 with django . I had a model when I used the feld FileField in order to get their facilities in the admin view, adn get a good user expieriece uploading photos from django.db import models from mezzanine.core.fields import FileField from mezzanine.utils.models import upload_to, AdminThumbMixin from django.contrib.auth.models import User # Create your models here. class Person(models.Model): full_name = models.CharField(max_length=256, null=True, blank=True) passport = models.CharField(max_length=128, null=True, blank=True) birth_day = models.CharField(max_length=128, null=True, blank=True) #models.DateField(null=True, blank=True) address = models.TextField(null=True, blank=True) gender = models.CharField(max_length=128, choices=(('F', 'Female'), ('M', 'Male'), ('U', 'Ungendered'))) city = models.CharField(max_length=128, null=True, blank=True) country = models.ForeignKey(Country, null=True, on_delete=models.CASCADE) image = FileField("Image", upload_to=upload_to("api.models.image", "models"), format="Image", max_length=255, null=True, blank=True) But I would like to create a command to upload quickly a bunch of data of person from a csv and also upload the corresponding photos. I copied the photos to settings.MEDIA_ROOT in folder of photos uploaded. And I would like programmatically add the corresponding photo for each person. I try to test with python manage.py shell >>> from apps.api.models import Person >>> from django.conf import settings >>> from os.path import isfile, join >>> p1 = Person.objects.filter(first_name="Amanda Vega") >>> p1[0].image.save('amanda1', open(join(settings.MEDIA_ROOT,'uploads/image/estudio_50_photos_mod/1/profesional/_Y2B1035.JPG')).read()) Traceback (most recent call last): File "<console>", line 1, in <module> File … -
How not to deploy under git control db.sqlite3 file
In my django project, db.sqlite3 is under git control(I chose to do so). However when deploying the project to AWS server(using elastic beanstalk), I would like not to deploy db.sqlite3 file. Database setting is configured inside settings module so even db.sqlite3 file is deployed to the server, the project won't reference db.sqlite3 file. I will probably work fine but I do not want to deploy something unnecessary(db.sqlite3) to be deployed to the server. How can I not to deploy db.sqlite3 under git control? -
how to use verbose name in foreign key django admin?
how to use verbose_name in foreign key django admin?? class ParentsProfile(models.Model): Fathers_Firstname = models.CharField(verbose_name="Firstname", max_length=500,null=True,blank=True) Fathers_Middle_Initial = models.CharField(verbose_name="Middle Initial", max_length=500,null=True,blank=True, help_text="Father") Fathers_Lastname = models.CharField(verbose_name="Lastname", max_length=500,null=True,blank=True) Educational_AttainmentID_Father = models.ForeignKey(EducationalAttainment,on_delete=models.CASCADE,null=True,blank=True) I've already try to use Educational_AttainmentID_Father = models.ForeignKey("EducationalAttainment",EducationalAttainment,on_delete=models.CASCADE,null=True,blank=True) but it doesn't work -
Having trouble restricting editing to the owner of the profile in Django while using a custom user model
I am new to development and Django. This is my first project from scratch. I am also new on here, so if I don't ask a question correctly, please give me some feedback rather than downvoting. So, I decided to go with a custom user model so I could customize the registration page and require users to submit a photo during registration. I am not sure if I needed to go through all this just for that, and I am finding out that it's more difficult to manage a custom user class. Right now, I am attempting to only allow the current logged in user to be able to edit their own info, not anyone else's. I totally know how to do this through the normal User model, but I can't figure out how to do this through the custom user model path. The only way I know how to do this is to create a separate model that has a foreign key to my Profile model, 'owner', and compare the two ID's when the current user try's to edit someone else's profile. I looked around a couple different related questions, and I couldn't come up with a solution either. … -
List of contacts per User when extending AbstractUser
I want to create a custom user model with some extra fields, among which a contact list of other users. I would like to extend AbstractUser instead of creating a new model with a one-to-one link to User. from django.contrib.auth import get_user_model from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): a_custom_field = models.IntegerField(default=0) # per-user contact list contacts = models.ManyToManyField(get_user_model()) This code doesn't work. Throwing this error during makemigrations. django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.CustomUser' that has not been installed The error totally makes sense, but what's the right way to achieve this? -
Django access media/uploaded images from template
This is Post model class Post(models.Model): objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') thumbnail = models.ImageField(name="photo", upload_to='thumbnails/', null=True, default='default.png') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) This is my view for it class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' def get_context_data(self, **kwargs): obj = Settings.objects.get(pk=1) context = super().get_context_data(**kwargs) context["blog_name"] = getattr(obj, "blog_name") context["footer"] = getattr(obj, "footer") context["description"] = getattr(obj, "description") context["keywords"] = getattr(obj, "keywords") return context I already tested uploading images and such and they work fine and I can even load them by manually specifying the path (ie: /uploads/thumbnails/XXXXX.jpg) However I need to access them via my template with something like {{post.thumbnail.url}} -
File Structure Issue When Deplying Django React App to Heroku
I have a Django React project that I created from a tutorial. I have played around with the Procfile and wsgi file quite a bit, but cannot seem to get the files correctly written to navigate my project structure. I can run my project locally with two terminal tabs. One is python manage.py runserver in lead_manager/leadmanagerproject The other tab is npm run dev in lead_manager/leadmanagerproject/frontend I haven't even gotten to the React side of things, just trying to get the Django part of the project working and I can't seem to get the Procfile and wsgi file done correctly. Any help/advice is greatly appreciated! Let me know what other information might help - I am new to Stack Overflow. Project Structure lead_manager | .gitignore | .babelrc | db.sqlite3 | requirements.txt | runtime.txt | package-lock.json | package.json | Pipfile | Pipfile.lock | Procfile | webpack.config.js | \---staticfiles | \---leadmanagerproject | db.sqlite3 | manage.py | +---accounts | | admin.py | | apps.py | | api.py | | models.py | | serializers.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations +---frontend | | admin.py | | apps.py | | models.py | | tests.py | | … -
Sending a Python Dictionary Through a Single POST method in Django REST Framework
I have been attempting to implement this method several ways in which seems like it should be pretty straightforward. I have a web scraper that scrapes stock data and stores it into a Python dictionary in a python script. This then makes a post request to my Django API which is handled under my views using GenericAPIView. This post request sends a QueryDict and I am able to post a single instance but not multiple at once. Yes, I have said many=True on my serializer and attempted to override these methods. Each solution I have made is inefficient and I am frustrated not finding a clear and simple solution. This is my first time working with the Django Rest Framework so bear with me and thanks for your help in advance! CryptoView.py (Mostly followed a tutorial on Medium.com to improve my method) class CryptoView(ListCreateAPIView): queryset = Crypto.objects.all() serializer_class = CryptoSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class SingleCryptoView(RetrieveUpdateDestroyAPIView): queryset = Crypto.objects.all() serializer_class = CryptoSerializer Cryptotest.py crypto = { "id": [], "name": [], "price": [], "change": [], "percentChange": [] } # For Loop - Yahoo Finance requires us to …