Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to edit the Django Admin User social auths listing page?
I am having trouble finding where this admin file exists so I can add an extra field. I think it's auto-magically created upon setup. I want to add a date field, specifically, to the listing page (shown below), perhaps after the UID field so I can know when the user auth was created. screenshot of django user social auths listing page -
App name not registering when running server in DJANGO
I am trying to make a simple rest API with Django and am having trouble whenever I am running the server. I get the error that my leads module does not exist and I created that app with the python manage.py startapp leads and the installed Apps section in my settings.py file look like this INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'leads.apps.LeadsConfig', # I also tried `leads` and that doesnt work as well 'rest_framework' ] my project directory looks like this manager leads migrations __init__.py admin.py api.py apps.py models.py serializer.py tests.py urls.py views.py manager __init__.py asgi.py settings.py urls.py wsgi.py manage.py Pipfile Pipfile.lock As you can see I have the init.py file and that is empty and I do not know why my leads app is not a module that can be used? someone please help. thank you -
Nginx routing Django Web App links to wrong path
I have a django app where the hompage routes correctly, but when I try to click on any of the links I get a 404 error. I looked at the logs and see: *1 open() "/usr/share/nginx/html/pricing" failed (2: No such file or directory) which tells me that nginx is not looking at my project folder but instead what seems to be a default setting. I am using centos, so I had to manually setup sites-available and sites-enabled, which I have used to get the homepage working. As such there is no default conf to disable. I am unsure how to get nginx to route to my path instead of the default. My nginx.conf file looks like this: user so_dev; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; #added by me } -
Execute function at special time using Django
I write task manager, and i want to create bot, which must send message to user (maybe user's email or social account). I want to user can be able choose task and set time, when bot should send message to him. My proble is that I don't know what i can user for it, I use django framework, and now i think that celery can help me with it. -
Django 'User' object has no attribute 'UserProfile'
Im working on a django project and I have a UserProfile that looks like this: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_image_path,null=True,blank=True, default="") username = models.CharField(max_length=200,null=True,blank=True) def get_absolute_url(self): return reverse_lazy("accounts:detail", kwargs={"username":self.user.username}) I am working on the userprofile view: class UserDetailView(RetrieveUpdateAPIView): queryset = User.objects.all() serializer_class = UserThumbSerializer renderer_classes = [TemplateHTMLRenderer] lookup_field = 'username' template_name = "userprofile.html" def get(self, request, username=None): user_ = get_object_or_404(User, username=username) image = user_.UserProfile.image serializer=UserThumbSerializer() return Response({'serializer':serializer,'image':image}) def post(self, request, username=None): user_ = get_object_or_404(User, username=username) image = user_.UserProfile.image serializer = UserThumbSerializer(data=request.data) if not serializer.is_valid(): return Response({'fields':serializer,'image':image}) serializer.save() return redirect('/') This is the serializer for the image of the userprofile class UserThumbSerializer(ModelSerializer): class Meta: model = UserProfile fields = ['image'] This is the form to update the userprofile image: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Send"> </form> I want to update the image of the UserProfile but I get this error: Traceback (most recent call last): File "C:\...\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\...\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\...\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\...\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\...\lib\site-packages\django\views\generic\base.py", line 71, in … -
Django pandas rest and routers
Is there any example or documentation, where I could understand, how does work pandas_rest along with django-rest routers together? How to identify URL, where e.g. csv file will be produced? The documentation is not too verbose to this point https://github.com/wq/django-rest-pandas#registering-urls -
Scope of worker_exit of Gunicorn
I am using Gunicorn to deploy an Django app. There is a global singleton variable defined in util.py: global SNS_PRODUCERS SNS_PRODUCERS = {} def close_producers(): logger.info('Closing all producers...') global SNS_PRODUCERS for name, producer in SNS_PRODUCERS.items(): producer.close() I would like to call close_producers when my app shutdown. I added the following into gunicornconf.py: def child_exit(server, worker): # Join background threads in util.SNS_PRODUCERS try: from util import close_producers close_producers() except: pass def worker_exit(server, worker): try: from util import close_producers close_producers() except: pass My understanding is that, there is one master process, and multiple worker process forked from master process. In each process, util.py is imported to this process. So, there are multiple SNS_PRODUCERS in these process, one SNS_PRODUCERS in one worker or master process. Each worker process has ITS OWN worker_exit. The master process has ITS OWN child_exit. When one worker is shutdown, its worker_exit is called, and then ITS OWN SNS_PRODUCERS is closed. Other SNS_PRODUCERS are still open. Am I right? Any corrections are welcomed. -
Get related objects through FK of a FK in django (will a _set work?)
If I had a model structure like this: class Camp(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200, blank=True, null=True) reg_start = models.DateTimeField() reg_end = models.DateTimeField() class Course(models.Model): camp = models.ForeignKey(Camp, on_delete=models.PROTECT) name = models.CharField(max_length=100) description = models.CharField(max_length=500, blank=True, null=True) class ClassDetail(models.Model): course = models.ForeignKey(Course, on_delete=models.PROTECT) seat_count = models.IntegerField() limit_registrations = models.BooleanField(default=False) class Registration(models.Model): person = models.ForeignKey(User, on_delete=models.PROTECT) class_detail = models.ForeignKey(CourseDetail, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) If I had a user that had (potentially) multiple Registrations, is there a quick and easy way to get a list of the id's of those camps? This is what I currently have (which is working but I'm trying to see if I can eliminate the list comprehension) registration_queryset = Registration.objects.filter( person__id=user_id ) camps_to_exclude = [ x.course_detail.course.camp.id for x in registration_queryset ] # camp_list is an already existing queryset of camps camp_list = camp_list.exclude( id__in=camps_to_exclude, ) -
Django trying to upper(integer) in Postgres causing "no function matches the given name and argument types"
Django==3.0.3 djangorestframework==3.11.0 psycopg2-binary==2.8.4 sqlparse==0.3.0 Using Postgres 11 and Python 3.8. The field in question is the following in the model: class User(AbstractUser): id = models.AutoField(primary_key=True) This is the serializer: class SetupUserSerializer(serializers.Serializer): id = serializers.IntegerField(write_only=True) def validate(self, data): user_qs = USERS.objects.filter(id__iexact=data['id']) if user_qs.exists() and user_qs.count() == 1: user_obj = user_qs.first() # do some stuff When run it gets to the if user_qs.exists() and user_qs.count() == 1: and the following error comes up: The above exception (function upper(integer) does not exist LINE 1: ...a" FROM "users" WHERE UPPER("users"."id"::text) = UPPER(1021... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. ) was the direct cause of the following exception: Not sure why it is casting to text and trying to make uppercase. This is the JSON being sent: { "id": 123456 } This is the traceback: File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch response = … -
Getting error in bash while deploying site
I am entirely new to django/python/web development and following django girls tutorial. In bash (of pythonanywhere) when i try to run this command pa_autoconfigure_django.py --python=3.6https://github.com/myuserid/my-first-blog.git I get pa_autoconfigure_django.py [--domain= --pytho n=] [--nuke] What is the meaning of this? In actual this should happen Downloading your code from GitHub Creating a virtualenv on PythonAnywhere, just like the one on your own computer Updating your settings file with some deployment settings Setting up a database on PythonAnywhere using the manage.py migrate command Setting up your static files And configuring PythonAnywhere to serve your web app via its API -
How to serve pdf files stored in s3 bucket from views.py
I'm quite new to django and currently working in a project that includes serving pdf files using FileResponse method. In development environment it was all great, since the files was stored in the project directory. Now in production, I am storing these files in a S3 bucket, just to keep things separate. But I cannot see a way to effectively access the files from my app. I've tried things like: s3 = boto3.resource('s3') obj = s3.Object(bucket_name, file) body = obj.get()['Body'].read() But this does not seem to work with binary files... I was thinking about downloading the files to /tmp directory, but it got be a better way... Any help or guidance will be appreciated. Thanks in advance. -
Why do queryset[0] and queryset.first() return different records?
I discovered today that I can access elements in a queryset by referencing them with an index, i.e. queryset[n]. However, immediately after I discovered that queryset[0] does not return the same record as queryset.first(). Why is this, and is one of those more "correct"? (I know that .first() is faster, but other than that) Python 3.7.4 django 1.11.20 -
How is the best way to manage files on a Django download portal
I am using Django to create a kind of download portal. What is the best way to manage the files effectively and efficiently? -
How to get data from your mangoDB using django?
so i want to get some data that i saved in my MongoDB using a python Script and i'm don't really know how to do that, anyways here is the script that saves my json file into my Database . And Yeah i'm using the same database with my django project from pymongo import MongoClient import json from shutil import copyfile import osclient = MongoClient('localhost',27017) db = client['Comments_database'] comment = db['comment'] for file in os.listdir("path"): if file.endswith(".json"): with open(file,encoding='utf8') as f : file_data = json.load(f) comment.insert_one(file_data) copyfile(file,"saved\\"+file) os.remove(file) client.close() My MongoDB -
Using filter_horizontal, is there a way to control what is displayed on the widget?
When I use the filter_horizontal in Django, the filter creates a widget with the model primary-key names. However, I want to display something different, such as a different field. Is there any way to do that? -
Method Not Allowed (POST): /home/
I have a one page app with a form and a data table. The page load fine, but the problem is the Form is not working when I press the "SUBMIT" Button. When I press the "SUBMIT" Button it give me this error Method Not Allowed (POST): /home/ Thanks you for the help guys! views.py def _get_form(request, formcls, prefix): data = request.POST if prefix in request.POST else None return formcls(data, prefix=prefix) all_items = List.objects.all class Myview(TemplateView): template_name = 'data_list/home.html' all_items = List.objects.all def get(self, request, *args, **kwargs): return self.render_to_response({'scrap': Scrap(prefix="scrap_pre"), 'all_items': all_items}) def scrap(self, request, *args, **kwargs): scrap = _get_form(request, Scrap, 'scrap_pre') if request.method == "POST": scrap = _get_form(request, Scrap, 'scrap_pre') if scrap.is_valid(): print("Worked") return self.render_to_response({'scrap': scrap}) def home(self, request, *args, **kwargs): all_items = List.objects.all return render(request, "data_list/home.html", {"all_items": all_items}) forms.py class Scrap(forms.ModelForm): url = forms.CharField() class Meta: model = List fields = ["item", "site"] urls.py from django.urls import path, include from . import views urlpatterns = [ path("", views.add, name="add"), path("scrap/", views.scrap, name="scrap"), path("home/", views.Myview.as_view(), name="home"), path("delete/<list_id>", views.delete, name="delete"), path("datacontent/<list_id>", views.datacontent, name="datacontent") ] home.html <div> <form action="" method="post" > {% csrf_token %} {{ scrap|crispy }} <pre></pre> <button class="btn btn-outline-info" type="submit" value="Submit">SUBMIT</button> <pre></pre><pre></pre><pre></pre><pre></pre> </form> </div> <table class="table"> ..... -
Require multiple entries for "Item", Django Admin
I want to enter multiple entries for "item" under one "session_title" - and I think I understand I need a ManyToOne relationship (set with ForeignKey) but mysite/admin isn't showing multiple entries available? I am using DjangoAdmin to administer my app. class Item(models.Model): item_name = models.TextField(unique=True) class Meta: managed = True db_table = 'item' def __str__(self): return self.item_name class SessionLog(models.Model): date = models.DateField() session_title = models.TextField(blank=True, null=True) campaign = models.OneToOneField(Campaign, models.DO_NOTHING, default="1") chapter = models.OneToOneField(Chapter, models.DO_NOTHING, default="1") scene = models.OneToOneField(Scene, models.DO_NOTHING, default="1") character = models.OneToOneField(Character, models.DO_NOTHING, default="1") location = models.OneToOneField(Location, models.DO_NOTHING, blank=True, null=True) npc = models.OneToOneField(Npc, models.DO_NOTHING, blank=True, null=True) monster = models.OneToOneField(Monster, models.DO_NOTHING, blank=True, null=True) item = models.ForeignKey(Item, models.DO_NOTHING, blank=True, null=True) loot_pp = models.IntegerField(blank=True, null=True) loot_gp = models.IntegerField(blank=True, null=True) loot_ep = models.IntegerField(blank=True, null=True) loot_sp = models.IntegerField(blank=True, null=True) loot_cp = models.IntegerField(blank=True, null=True) session_xp = models.IntegerField(blank=True, null=True) session_strongstart = models.TextField(blank=True, null=True) session_secrets = models.TextField(blank=True, null=True) session_clues = models.TextField(blank=True, null=True) session_notes = models.TextField(blank=True, null=True) class Meta: managed = True db_table = 'session_log' def __str__(self): return self.session_title Could someone point me in the right direction? Thank you, in advance. -
Django- order by a field unless it is null, then use another
Lets say I have the following model: class MyModel(models.Model): name = models.CharField(max_length=255) date_1 = models.DateField(null=True, blank=True) date_2 = models.DateField(null=True, blank=True) Each model will have at least 1 of the date fields. What I want to do is order by the following- if the model has date_1, order it by date_1. If it does not have date_1, instead order it by date_2. Doing something like this: MyModel.objects.all().order_by('date_1', 'date_2') will stick all of the null date_1 values to the end. Whereas I would like to have the "interleaved". For example, I would want the following output (in json format): [ {"id": 1, "date_1": "2020-02-01", "date_2": null}, {"id": 4, "date_1": null, "date_2": 2020-02-02}, # orders by date_2 as there is no date_1 {"id": 2, "date_1": "2020-02-03", "date_2": "2020-02-01"}, # orders by date_1, ignores date_2 {"id": 3, "date_1": "2020-02-04", "date_2": null}, ] Is this possible to do with the django ORM? -
Django: NOT NULL constraint failed - Working for one field but not for the other
I'm getting the error: NOT NULL constraint failed: issues_issue.project_id when trying to create an instance of the model Issue The issues have a Foreign key to project, and I assign it in the form_valid method, I do the same with the user and that works fine Views.py: model = Issue fields = ['title', 'details', 'priority', 'status', 'estimated_work_hours', 'loaded_work_hours'] def form_valid(self, form): form.instance.project = get_object_or_404(Project, pk=self.kwargs['project_id']) print(form.instance.project) form.instance.creator = self.request.user return super().form_valid(form) The line print(form.instance.project) prints the correct project so that is working. models.py: class Issue(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) creator = models.ForeignKey(User, related_name="%(class)ss_created", on_delete=models.CASCADE) ... ... I really don't understand why I'm still getting the error Thanks -
How to create input filter in Django with option to specify filtering option
I am trying to add an input filter to my Django admin that has two parts: A dropdown list (select) with filtering options like: contain, equals, starts with, ends with An input box for the user to input what they are looking for I followed this artical https://medium.com/@hakibenita/how-to-add-a-text-filter-to-django-admin-5d1db93772d8 to create the input filter. I know how to change the template to add the dropdown list however I cannot get the functionality to work. Any ideas how to get this done ? -
Django: returning __str__ error when I try to add new instance of model from admin dashboard
When I try to add a new instance of any model that has Campus as a foreign key, I get this error, and I'm dumbfounded. Here is the code for the Campus model from django.db import models class Campus(models.Model): name = models.TextField(max_length = 100, default=None) description = models.TextField(max_length = 100, default=None) def __str__(self): return self.name I'm not sure what the problem is with the str function as this is what I do for all of my basic models. Thanks for any help you can give -
Django Recursive Annotation
I'm building a Django app with a recursive comment structure. Problem: The recursive nature of my comments datastructure means I'm struggling to write a query to annotate each post with the number of replies, and then traverse those posts/replies in my template. The comment model I've built differentiates between post responses (which are top level comments) and comment responses (which are replies to other comments). (Post) 3 Total Comments ----------------- one (post reply) └── two (comment reply) └── three (comment reply) (more) I've represented a comment as follows: class Comment(TimeStamp): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content = models.TextField(max_length=2000) post = models.ForeignKey("Post", on_delete=models.CASCADE, related_name="comments") # Top level comments are those that aren't replies to other comments reply = models.ForeignKey( "self", on_delete=models.PROTECT, null=True, blank=True, related_name="replies" ) This works pretty well, pic related What works I'm able to prefetch all the comment replies for a post as follows: comment_query = Comment.objects.annotate(num_replies=Count("replies")) post = Post.objects.prefetch_related(Prefetch("comments", comment_query)).get(id="1") Which correctly displays the number of replies for each comment: >>> post.comments.values_list('num_replies') <QuerySet [(1,), (1,), (0,)]> What Doesn't Work This query only annotates the top level post.comments >>> post.comments.first().replies.all() <QuerySet [<Comment: two>]> >>> post.comments.first().replies.first().num_replies --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-132-8151a7d13021> in <module> ----> 1 post.comments.first().replies.first().num_replies AttributeError: … -
Django models.py does not have pk
I am creating a blog app. In this app, users create blog posts and see those. I have a problem to let the posts have its url related with pk and slug. models.py class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) image = models.ImageField(null=True, blank=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=False) def __str__(self): return self.title def get_absolute_url(self): print(self.pk, self.slug) return reverse('blog:detail', kwargs={ 'pk': self.pk, 'slug': self.slug }) views.py app_name = 'blog' urlpatterns = [ path('create/', create_blog_view, name="create"), path('<pk>/<slug>/', detail_blog_view, name="detail"), path('<slug>/edit/', edit_blog_view, name="edit"), ] The problem is that models.py only has slug not pk. So it fails to create the url. How could I do with this problem? Thank you in advance. -
Django timezone in admin interface is not mine: how do I change it?
In my models I have this: created_at = models.DateTimeField(auto_now_add=True) If I display created_at in my django-admin dashboard, it is always lagging by 1 hour. How can I avoid this? How can I display the datetime in my timezone? My timezone is GMT+1 If I type date in my server terminal, I get the correct datetime. I've consulted the documentation and it says I have to use the activate() function, without specifying where I should actually use it and how: there are no examples and it's very confusing. -
Django filter manytomany relation
I spent a lot of time trying to filter out the entities related many to many, but the result really amazes me. I can’t understand how to solve this and why this happens. I have 2 models in Django: class Application(models.Model): ... forms = models.ManyToManyField(Form, related_name='applications', through='ApplicationForm', blank=True) ... class Form(models.Model): ... class ApplicationForm(models.Model): application = models.ForeignKey(Application, on_delete=models.CASCADE) form = models.ForeignKey(Form, on_delete=models.CASCADE) created_at = models.DateTimeField() updated_at = models.DateTimeField(auto_now=True) In ApplicationSerializer I want to return filtered forms related to my application. I try to do this on this way: forms = serializer.SerializerMethodField() def get_forms(self, obj): qs = obj.forms.filter(status=Form.COMPLETED) return FormSerializer(qs, many=True, context=self.context).data I have 2 forms and 3 applications which has both forms. But my function returns 6 forms [1, 2, 1, 2, 1, 2] for example. I try to debug this and found that obj.forms.all() return 2 forms, but if I add filter it returns 6. I try to use obj.forms.filter(status=Form.COMPLETED).distinct() but result the same. I can not create query like Forms.objects.filter(status=Form.COMPLETED).filter(pk__in=...) because i have many parameters prefetched and annotated on application manager level. So I want to know is there any way to filter manytomany relation objects related to my instance