Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SSH Connect to AWS EC2 failed after using lets-encrypt update my website
Yesterday, I updated my Django website (on AWS EC2) to HTTPS by using lets-encrypt. Everything works well. The website has HTTPS green icon as expected. Today when I try to connect my instance by using SSH. The connection failed. It give some message like "ssh: Could not resolve hostname blog_project.pem: Name or service not known". I thought it might be security group problem of this instance. So I double checked my security group setting of this instance, the SSH, HTTP and HTTPS port are all open correctly. I created another instance to test if there is any problem on my local. The new instance connected successfully. Now I am really confused. My local machine is Windows subsystem of Linux. My EC2 instance is Ubuntu 16. I am using Nginx as web server. My ssh "command is ssh -i blog_project.pem root@ec2-34-202-93-189.compute-1.amazonaws.com" Thank you for the help. -
Filter foo_set in django-mptt
Existing 3 models: class Category(MPTTModel): title = models.CharField(_("Title"), max_length=128) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class Contract(models.Model): category = models.ManyToManyField(Category, verbose_name=_("Category")) class Task(models.Model): category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True) contract = models.ForeignKey(Contract, verbose_name=_("Contract")) I want to get via mptt dicts with foo_set model: [ if has parent category here will be wrapper dict, and level above, etc. { "id": 15, "name": "title", "children": { "task": [{"id": 6}, {"id": 7}], "id": 14, "name": "and title" }, } { "id": 10, "name": "title", "children": { "task": [{"id": 2}, {"id": 3}, {"id": 4}], "id": 16, "name": "any title" }, } ... ] or simple [ category 1.1, category 2.1, category 2.2, category 3.1, category.foo_set.filter(any) [1,2,3...] ... category 2.3, category 1.2 ] And i want to get different filter with different data. One data by contract, second by category via IF. def view(request): contract = request.GET.get('contract', None) category = request.GET.get('category', None) if contract: obj = get_object_or_404(Contract, id=contract) category_ids = [n.category_id for n in obj.task_set.filter(contract=obj.id).select_related('contract')] nodes = Category.objects.filter(id__in=[n.id for n in obj.category.all()]).prefetch_related('task_set') if category: obj = get_object_or_404(Category, id=category) nodes = obj.get_descendants().prefetch_related('task_set') def recursive_node_to_dict(node): result = { 'id': node.pk, 'name': node.title, 'task': [] } if for c in node.get_descendants(): result['children'] = recursive_node_to_dict(c) if contract: result['task'] … -
Getting a private chat-room based on either one of two users
I understand I need to add users into a specific Group to allow the users within that group to message each other, but I can't wrap my head around more dynamic access. For example, if I'm trying to hold a private chat room with the two allowed users into the chat-room to be predetermined, allowing access to nobody else, how would I do this within the consumer(or helper function)? I have this (project specific) model that designates two users of a "Pair": class Pair(models.Model): requester = models.ForeignKey(Profile, related_name='is_requester') accepter = models.ForeignKey(Profile, related_name='is_accepter') And the models for a chat Room and the Message: class Room(models.Model): pair = models.ForeignKey(Pair, related_name='pair_to') date_started = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255) @property def websocket_group(self): """ Returns the Channels Group that sockets should subscribe to to get sent messages as they are generated. """ return Group("room-%s" % self.id) # def send_message(self, message, user, msg_type=MSG_TYPE_MESSAGE): # """ # Called to send a message to the room on behalf of a user. # """ # final_msg = {'room': str(self.id), 'message': message, 'username': user.username, 'msg_type': msg_type} # # Send out the message to everyone in the room # self.websocket_group.send( # {"text": json.dumps(final_msg)} # ) class Message(models.Model): chat = models.ForeignKey(Chat) sender = … -
Page not found when linking to a PDF in Django
How do I link to a pdf file in Django? I get an error message when I try and link to a PDF in a Django project. I'm not sure if its a problem with the code or if the virtual environment has to be configured to display pdf's. Error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/writing/static/writing/CatsSongbook.pdf Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: ^admin/ ^ ^$ [name='index'] ^ ^contact/ [name='contact'] ^blog/ ^writing/ ^$ [name='writing'] ^writing/ ^$ [name='book1'] The current path, writing/static/writing/CatsSongbook.pdf, didn't match any of these. writing urls.py from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.writing, name='writing'), url(r'^$', views.book1, name='book1'), ] Urls.py from django.shortcuts import render def writing(request): return render(request, 'writing/writing.html') def book1(request): return HttpResponse(pdf, '.static/writing/pdf/CatsSongbook.pdf') Link in writing template. <a href="./static/writing/CatsSongbook.pdf" target="_top">book1</a> -
Failed to install pandas 0.22 version with pip
Tried to install pandas 0.22 to pythonanywhere and other linux server but failed. My command used: pip install pandas==0.22 pip install pandas Error Message: Running setup.py bdist_wheel for pandas ... -^error Failed building wheel for pandas We installed requirements.txt. Only pandas fail and other success. Django==2.0 django-chartjs==1.2 mysqlclient==1.3.12 Cython numpy==1.13.3 python-dateutil==2.6.1 pytz==2017.3 six==1.11.0 xlrd==1.1.0 gunicorn==19.7.1 dj-database-url whitenoise pandas==0.22.0 So any solution to install pandas? Don't wanna use conda due to limited environment. -
Django URL pattern for an unusual address
Which regular expression do I write in my URLs to give me this 'host:8000/"?page=1" ' in my browser address -
django queryset group by field
i have a listview and want to group by based on foreign key id views.py class SelectListView(ListView): model=MyModel template_name = "/select_list.html" context_object_name = 'selectlist' queryset = MyModel.objects.all().values('ItemType_id') paginate_by = 10 def get_context_data(self, **kwargs): context = super(SelectListView, self).get_context_data(**kwargs) context['range'] = range(context["paginator"].num_pages) return context models.py class ItemType(models.Model): ItemType=models.CharField(unique=True,max_length=40) class MyModel(models.Model): Type=models.ForeignKey(ItemType) ItemName=models.CharField(unique=True,max_length=40) Question: I would like to group by the queryset by ItemType_id in the MyModel Expectation: select * from MyModel group by ItemType_id -
ValueError at /app/recomment/1/
I got an error,ValueError at /app/recomment/1/ Cannot assign "": "ReComment.target" must be a "POST" instance.The error is happened when I put Recomment button.I wanna make a page which is shown comment&recomment.I wrote codes in views.py class DetailView(generic.DetailView): model = POST template_name = 'detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_form'] = CommentCreateForm() context['recomment_form'] = ReCommentCreateForm() return context class CommentCreateView(generic.View): def post(self, request, *args, **kwargs): form = CommentCreateForm(request.POST) post = POST.objects.get(pk=kwargs['post_pk']) if form.is_valid(): obj = form.save(commit=False) obj.target = post obj.save() return redirect('detail', pk=post.pk) class ReCommentCreateView(generic.View): def post(self, request, *args, **kwargs): form = ReCommentCreateForm(request.POST) comment = Comment.objects.get(pk=kwargs['comment_pk']) if form.is_valid(): obj = form.save(commit=False) obj.target = comment obj.save() return redirect('detail', pk=comment.target.pk) def recomment(self, form): comment_pk = self.kwargs['pk'] comment = Comment.objects.get(pk=comment_pk) self.object = form.save(commit=False) self.object.target = comment self.object.save() return redirect('detail', pk=comment.target.pk) in urls.py from django.urls import path from django.conf import settings from . import views urlpatterns = [ path('detail/<int:pk>/', views.DetailView.as_view(), name='detail'), path('comment/<int:post_pk>/',views.CommentCreateView.as_view(), name='comment'), path('recomment/<int:comment_pk>/', views.ReCommentCreateView.as_view(), name='recomment'), ] in detail.html {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>DETAIL</title> </head> <body> <div id="comment-area"> {% for comment in post.comment_set.all %} <div class="media m-3"> <div class="media-body"> <h5 class="mt-0"> <span class="badge badge-primary badge-pill">{% by_the_time comment.created_at %}</span> {{ comment.name }} <span class="lead text-muted">{{ comment.created_at }}</span> <a href="{% url 'recomment' … -
is any way to use a 32bit anaconda in anaconda 64bit ver without download it
Could you get me some help? My os is window7 64bit I already downloaded anaconda 64bit to develope some web project with django. And sure I've runned other practices in here by myself. While using anaconda in this enviroment I wanna try an stock firm api with anaconda, but the matter is it only supplys for 32bit anaconda. Should I have to download 32 ver again, using a 64bit anaconda though? if there's way to use anaconda 32bit ver in 64 bit anaconda? Could you teach me how to do that? Please tell me if somebody knows. -
Update the instance after save, using signals by conditionally refference back to the instance in some cases
I have the following abstract class: class UserStamp(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='%(app_label)s_%(class)s_updated_by', on_delete=models.CASCADE) class Meta: abstract = True I have a custom User that inherits from User. class User(AbstractBaseUser,PermissionsMixin, UserStamp): account = models.ForeignKey(Account, blank=True, null=True, related_name='owner',on_delete=models.CASCADE) The User can create/update himself or by other user. When the user create/update himself I don't have anything for created_by, update_by. I thought on using a post_save signal, get the instance and update/those value, but I don't know in a post_save signal when is create or update. The post_save signal I don't need it if is create by another user, can be called conditional ? In a form that I create I can check if is created/updated by other user in the View, but that is not the case for Django Admin. -
Django 2.0 - YearArchiveView doesn't return all dates
Using the examples of the official documentation on YearArchiveView, I can't retrieve all dates from <ul> {% for date in date_list %} <li>{{ date|date }}</li> {% endfor %} this code. It only returns me the first date. I'm sure I have at least four more dates in my database because the following part <div> <h1>All Articles for {{ year|date:"Y" }}</h1> {% for obj in object_list %} <p> {{ obj.title }} - {{ obj.pub_date|date:"F j, Y" }} </p> {% endfor %} </div> returns me all the objects I have. My views.py file is like this: ... class ChatYearArchiveView(YearArchiveView): queryset = Chat.objects.all() date_field = "created_at" make_object_list = True allow_future = True Note: In my models.py, I made "created_at" as a DateTimeField(), not DateField() as the example said. Is this the problem? If so how should I change the code? -
Where to import stuff for a template in Django?
Sorry for the dumb question, I'm lost. I got a template and a templatetags with this : menu_tags.py from django import template from menu.models import Button register = template.Library() @register.inclusion_tag('menu/home.html') def show_menu(): buttons = Button.objects.all() return {'buttons': buttons} And this : home.html {% for button in buttons %} {% if user.is_authenticated %} stuff {% endif %} {% endfor %} I would like to know, how can I make user.is_authenticated work ? I know I have to import something, but where ? Importing it in menu_tags does not seems to work. Thanks ! -
Transfering a Digital ocean droplet to bluehost website
My name is omar. I have a django project that i created on my local machine. I created a docker image and container for my project and then ran the container that was created in my digital ocean droplet. I now want to have my website that I own to host the digital ocean droplet that was created. I have looked around but couldnt really find anything that helped me out in getting it running. I also had a few question that I couldnt find the answers to and was wondering if there was anyone that can help me out in any way find a solution or advice. How can i get my website to host the droplet that I created? When going from local machine to digital ocean droplet, does the database transfer over or is a new database created in the digital ocean droplet? If I have a live container and while it is live, information is stored in the database that is creates, and I update the container with a newer image with newer code, does the content from the original database go away and a new one is created, or is the database in a container … -
Nothing is happened when I put comment button
Nothing is happened when I put comment button.I wanna make a page which is shown comment&recomment.I wrote codes in views.py class DetailView(generic.DetailView): model = POST template_name = 'detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_form'] = CommentCreateForm() context['recomment_form'] = ReCommentCreateForm() return context class CommentCreateView(generic.View): def post(self, request, *args, **kwargs): form = CommentCreateForm(request.POST) post = POST.objects.get(pk=kwargs['post_pk']) if form.is_valid(): obj = form.save(commit=False) obj.target = post obj.save() return redirect('detail', pk=post.pk) class ReCommentCreateView(generic.View): def post(self, request, *args, **kwargs): form = ReCommentCreateForm(request.POST) comment = Comment.objects.get(pk=kwargs['comment_pk']) if form.is_valid(): obj = form.save(commit=False) obj.target = comment obj.save() return redirect('detail', pk=comment.target.pk) in urls.py from django.urls import path from django.conf import settings from . import views urlpatterns = [ path('detail/<int:pk>/', views.DetailView.as_view(), name='detail'), path('comment/<int:post_pk>/',views.CommentCreateView.as_view(), name='comment'), path('recomment/<int:comment_pk>/', views.ReCommentCreateView.as_view(), name='recomment'), ] in detail.html {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>DETAIL</title> </head> <body> <div id="comment-area"> {% for comment in post.comment.all %} <div class="media m-3"> <div class="media-body"> <h5 class="mt-0"> <span class="badge badge-primary badge-pill">{% by_the_time comment.created_at %}</span> {{ comment.name }} <span class="lead text-muted">{{ comment.created_at }}</span> <a href="{% url 'recomment' comment.pk %}">Recomment</a> </h5> {{ comment.text | linebreaksbr }} {% for recomment in comment.recomment.all %} <div class="media m-3"> <div class="media-body"> <h5 class="mt-0"> {{ recomment.name }} <span class="lead text-muted">{{ recomment.created_at }}</span> </h5> {{ recomment.text | linebreaksbr … -
How to setup django on apache
I've been trying to run django on apache but I keep on getting 504 Gateway Timeout. Here is the site conf. I've placed it in /etc/apache2/sites-available/ directory. <VirtualHost *:80> ServerName orounds.localhost DocumentRoot /var/www/html/orounds_pro WSGIScriptAlias / /var/www/html/orounds_pro/orounds_pro/wsgi.py WSGIDaemonProcess orounds processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/html/orounds_pro/venv/bin/python3 WSGIProcessGroup orounds <directory /var/www/html/orounds_pro> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /var/www/html/orounds_pro/static/ <Directory /var/www/html/orounds_pro/static> Require all granted </Directory> </VirtualHost> I'm using python3.6 and apache 2.4.29. I installed mod_wsgi for apache with sudo apt-get install libapache2-mod-wsgi-py3. Is there anything I'm doing wrong or is there anything else I should do? Regards. -
OperationalError at /app/comment/3/
I got an error,OperationalError at /app/comment/3/ table app_comment has no column named created_at.I wrote codes in views.py class DetailView(generic.DetailView): model = POST template_name = 'detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_form'] = CommentCreateForm() context['recomment_form'] = ReCommentCreateForm() return context class CommentCreateView(generic.View): def post(self, request, *args, **kwargs): form = CommentCreateForm(request.POST) post = POST.objects.get(pk=kwargs['post_pk']) if form.is_valid(): obj = form.save(commit=False) obj.target = post obj.save() return redirect('detail', pk=post.pk) class ReCommentCreateView(generic.View): def post(self, request, *args, **kwargs): form = ReCommentCreateForm(request.POST) comment = Comment.objects.get(pk=kwargs['comment_pk']) if form.is_valid(): obj = form.save(commit=False) obj.target = comment obj.save() return redirect('detail', pk=comment.target.pk) in urls.py from django.urls import path from django.conf import settings from . import views urlpatterns = [ path('detail/<int:pk>/', views.DetailView.as_view(), name='detail'), path('comment/<int:post_pk>/',views.CommentCreateView.as_view(), name='comment'), path('recomment/<int:comment_pk>/', views.ReCommentCreateView.as_view(), name='recomment'), ] in detail.html {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>DETAIL</title> </head> <body> <form action="{% url 'comment' post_pk=post.id %}" method="post"> {{comment_form}} {% csrf_token %} <input class="btn btn-primary" type="submit" value="comment"> </form> </body> </html> in models.py class Comment(models.Model): name = models.CharField(max_length=100, blank=True) text = models.TextField() target = models.ForeignKey(POST, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name When I put comment button, the error happens.I wrote created_at in Comment model, so I really cannot understand why this error happens.I designated detail.html in DetailView's class so I cannot … -
Saving user object to post Graphql/Apollo Vue
I am trying to save a user id to a new biz. I keep getting a 400 error and can not figure out why. I am using django for the backend with graphql and apollo client for the front with vue js. I am able to get the owner id but not able to save it for some reason. Create Biz Mutation Apollo export const CREATE_BIZ_MUTATION = gql` mutation CreateBizMutation($name: String!, $owner: ID!) { createBiz(name: $name, ownerId: $owner) { name } }` Create Biz mutation Django class CreateBiz(graphene.Mutation): id = graphene.Int() name = graphene.String() code = graphene.String() owner = graphene.Field(UserType) class Arguments: name = graphene.String() def mutate(self, info, name): user = get_user(info) or None code = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(6)) biz = Biz( code = code, name = name, owner = user ) biz.save() return CreateBiz( id= biz.id, name = biz.name, code = biz.code, owner = biz.owner ) Create Biz Component createBiz () { const owner = localStorage.getItem(DJANGO_USER_ID) if (!owner) { console.error('No user logged in') return } const { name } = this.$data this.$apollo.mutate({ mutation: CREATE_BIZ_MUTATION, variables: { name, owner } }).catch((error) => { console.log(error) }) } } -
Why do different Djano Models with JSONFields have the same values?
I've got a model with a JSONField (a Postgres only field): models.py: from django.db import models from django.contrib.postgres.fields import JSONField class Mod(models.Model): data = JSONField(default={ 'name':'Model' }) So I create 2 models – ./manage.py shell: >>> from m3d.models import Mod >>> m1 = Mod() >>> m1.save() >>> m2 = Mod() >>> m2.data['name'] = 'Model 2' >>> m2.save() But they have the same data['name'] values: >>> m1.data['name'] 'Model 2' >>> m2.data['name'] 'Model 2' Note that the values are different in the database: >>> m1a = Mod.objects.get(pk=m1.pk) # get m1 data from db >>> m1a.data['name'] 'Model' >>> m2.data['name'] 'Model 2' but the variable m1 still has the value Model 2. Am I missing something? Is this some sort behavior I'll need to work around? FYI: Using Django 2.0.1 -
Multiple Levels Of Inheritance Using Django Templates
I'm creating a Django project, where I want to use multiple levels of inheritance in my templates. E.g I want to do something like this: project_base.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> Then in app_base.html I extend this. {% extends "project/project_base.html" %} {% block title %}Generic Title{% endblock %} {% block content %} <img src="/dir/sub_dir/image.jpg"> {% block app_content %} {% endblock %} {% endblock %} Finally I have my actual template {% extends app_base.html %} {% block title %}Specific Title{% endblock %} {% block app_content %} {% for obj in objects %} <a href="{{ obj.get_absolute_url }}">{{ obj.name }}</a> {% endfor %} {% endblock %} The problem that I have is that when I go to load that page I see a single heading from an entirely unrelated template, and not my list of hyperlinks. What's the correct/best way to have multiple levels of inheritance for my template files? -
Jupyter notebook gets stuck running Django shell
I set up a basic Django app, and wanted to us Jupyter notebook to run a Django shell, but when I enter !python.manage.py runserver MY.IP.HERE:8000, jupyter gets stuck running, and there is nothing returned. I tried going to http://MY.IP.HERE:8000, but there's nothing available. -
Execute Python Scripts In Apache WebServer
I have a problem when execute python scripts in apache. I config htttp.conf like <VirtualHost *:80> ServerName xhentai69.com ServerAlias www.xhentai69.com <Directory /var/www/xhentai69.com> Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec Options +ExecCGI DirectoryIndex index.py </Directory> AddHandler cgi-script .py ServerAdmin webmaster@localhost DocumentRoot /var/www/xhentai69.com ErrorLog /var/www/xhentai69.com/error.log #CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> and index.py #!/usr/bin/env python print('Content-type: text/html\n\n') print('Hello') When I access http://xhentai69.com, it show 500 Internal Server Error and in file log AH01215: (2)No such file or directory: exec of '/var/www/xhentai69.com/index.py' failed: /var/www/xhentai69.com/index.py End of script output before headers: index.py But when i change to name home.py and config again httpd.conf DirectoryIndex home.py, it work. Why? -
Including another QuerySet in a Django DetailView
I am trying to include a "Related Shows" section to my website when someone looks at a show on the website. How can I implement this in my single show page? views.py: class ShowDetailView(DetailView): model = Show slug_field = 'show_slug' def show_detail_view(request, show_slug): try: show_slug = Show.objects.get(show_slug=show_slug).prefetch_related('show_tickets').prefetch_related('show_sponsor') except Show.DoesNotExist: raise Http404("Show does not exist") -
How are Ajax/Fetch calls different on production server vs. runserver for Django app?
How things are working on my development runserver: I have a Django app that updates a progress html tag using Ajax requests (currently I am using POST but I have used GET successfully as well on my development runserver). Everything works great. The Ajax request calls a function in my view.py that returns a JsonResponse with the updated data from my business logic happening in views. I am using setInterval with setTimeout to control the number of calls and clearInterval when I reach certain values. Production deployment to Heroku: I am currently trying to deploy to Heroku and have been 99% successful. My template renders correctly, so I can see my page and submit the form for processing. The 1% problem here is that my Ajax requests are not getting updated data and I don't know why. It's like my Ajax requests are just getting the initialized variable values of zero and continue to return those values. I am console.logging the JSON returned from the Ajax call: {games: 0, progress: 0, percentage: 0} {games: 0, progress: 0, percentage: 0} {games: 0, progress: 0, percentage: 0} {games: 0, progress: 0, percentage: 0} This JSON just gets returned over and over again … -
File upload doesn't terminate in Safari
I'm running a test server under the latest Django 2 release (Python3.6) on Mac OS X. My applications seem to work well across both Safari 11.0.2 and Chrome (build 63) except for one anoying detail. I've got this file upload form: class BulkForm(AssemblyForm): # AssemblyForm itself defines a Char field. file = forms.FileField(required=True, label='Input file') That is handled by the following view (I've reduced it to the bare minimum for this example): def formtest(request): if request.method == 'POST': form = BulkForm(request.POST, request.FILES) if form.is_valid(): upload = request.FILES['file'] return HttpResponseRedirect(reverse('submissions')) bulk = BulkForm() return render(request, 'upload.html', {'bulk_form': bulk}) And the template: ... <div class="tab-pane fade" id="bulk"> <div class="container my-4"> <form role="form" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ bulk_form.as_p }} <button type="submit" name="bulk-form" class="btn btn-primary bg-dark"> Submit </button> </form> </div> ... In Safari the upload sometimes freezes even when I try the same file: sometimes it uploads successfully, sometimes it freezes. There is a correlation between file size and its chances to get stuck. To investigate this issue, I've implemented my own upload handler: class SizeLimitedUploadedFile(uploadedfile.UploadedFile): def __init__(self, name, content_type, size, charset, content_type_extra=None): file = tempfile.NamedTemporaryFile( buffering=settings.FILE_UPLOAD_MAX_MEMORY_SIZE, delete=False, suffix=f'.upload.{name.split(".", 1)[1]}', dir=settings.FILE_UPLOAD_TEMP_DIR ) super().__init__(file, file.name, content_type, 0, charset, content_type_extra) self.error = None def … -
Django - Modifying string representation of User object globally (outside of admin, even) for use in Model Forms
My website has many ModelForms and whenever it has a Foreign Key property to the User model, the property displayed is username. How can I change that so that the representation is, instead, the user's full name (or something else)? I am preferably looking for a global solution, which will work for all model forms from here on, but I am not discarding a fix that involves customizing each form (rather than changing the model). I am working with a userprofile extension of the user model. The fix that I've tried so far is supplanting the str method in the user class. This is the snipped I have on the model class (taken from an entry of this forum, btw). This code is in the models.py file: #CUSTOMIZES REPRESENTATION OF USER def get_full_name(self): return self.first_name + ' ' + self.last_name User.add_to_class("__str__", get_full_name) Thank you!