Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django showing values of an annotated queryset without knowing the filed name
I´m building a dashboard where you can cross data from a sales database. For example, sales by seller, products by client, etc. I let the user choose both option 1 and option 2. I get the form back to the view and annotate the model with those options: if filter_opts.is_valid(): option_1 = filter_opts.cleaned_data["option_1"] option_2 = filter_opts.cleaned_data["option_2"] results = ventas.values(option_2).annotate(Count(option_1, distinct=True)) The annotation works fine and if I just print the queryset in the template {% for case in results %} {{ case }} {% endfor %} I can see it like: {'cliente': '502 EMSUR', 'prod_nombre__count': 9} Then in the template I want to show only the values. But I can´t tell forehand which would be the value name to do something like this: {% for case in results %} {{ case.option_1 }} {{ case.option_2 }} {% endfor %} If I iterate over the result I can see the field name: {% for case in results %} {% for item in case %} {{ item }} {% endfor %} {% endfor %} How can I show the values of that fields? Thanks! -
How do I pass command line arguments to my Python manage.py shell script?
I have a Python 3.7 / Django project using the auth module. I want to write a script to create users, but I'm very confused about how to do it. I have created this from django.contrib.auth.models import User import sys firstarg=sys.argv[1] secondarg=sys.argv[2] user=User.objects.create_user(firstarg, password=secondarg) user.is_superuser=False user.is_staff=False user.save() I would liek to pass a username and password argument to this script. I tried the below localhost:dental davea$ source venv/bin/activate; python manage.py shell < create_users.py "user1" "password" /Users/davea/Documents/workspace/dental/venv/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) usage: manage.py shell [-h] [--no-startup] [-i {ipython,bpython,python}] [-c COMMAND] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] manage.py shell: error: unrecognized arguments: user1 password but you can see the error it results in. How do I invoke my script from teh command line, while creating the virtual environment it shoudl be running in? -
Retrieving Django QuerySet matching field in reverse query (related_name)
I apologize for the title... it's really hard to explain my question in one line. I'm trying to determine a way to retrieve all objects of one model that match a field in another model through an objects related_name set. Examples of my models: class InvDetail(models.Model): sales_order = models.ForeignKey('SalesOrder', on_delete=models.SET_NULL, null=TRUE) [...]other invoice related fields[...] class SalesOrder(models.Model): [...]a bunch of sales order specific fields[...] class SOSeller(models.Model): sales_order = models.ForeignKey('SalesOrder', on_delete=models.CASCADE) salesperson = models.ForeignKey('UserProfile', on_delete=models.CASCADE) What I'm trying to get is all of InvDetail objects that are linked to SalesOrder objects that has a SOSeller object that is linked to a particular UserProfile object. In my case, an individual sales order can have multiple salesperson attached to it (in which case, they all get credit for commission purposes, for example) Right now, I am iterating through a for loop of all the InvDetails, (or really, filtered down to a particular date range, which I didn't show in my model). invdetails = InvDetail.objects.all() filtered_inds = [] for invdetail in invdetails: sellers = invdetail.sales_order.soseller_set.all().values_list('salesperson__user__username', flat=True) if name in sellers: filtered_inds.append(invdetail) This gets me a list of all of the invoices associated with a particular salesperson, but it is painfully slow, especially as the … -
jQuery's fadeToggle() selects more elements than desired
< script type = "text/javascript" > $(document).ready(function(event) { $(".reply-btn").click(function() { $(".section-row-reply").closest(".section-row-reply").fadeToggle(); }); }); < /script> I have a for-loop that generates the following: comments replies reply form. I want the jquery function,fadeToggle() to reveal the reply form for each comment when the reply button is clicked <!-- jquery 2.2.4 --> <script src="{% static 'js/jquery.min.js' %}"></script> <!-- bootstrap 3.3.7 --> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery.stellar.min.js' %}"></script> <script src="{% static 'js/main.js' %}"></script> <!-- post comments --> <div class="section-row"> <div class="section-title"> <h3 class="title">{{ comments.count }} Comment{{ comments|pluralize }}</h3> </div> <div class="post-comments"> {% for comment in comments %} {% if comment %} <!-- comment --> <div class="media"> <div class="media-left"> <img class="media-object" src="{{ comment.profile_picture.url }}" alt=""> </div> <div class="media-body"> <div class="media-heading"> <h4>{{ comment.user }}</h4> <span class="time">{{ comment.timestamp }}</span> </div> <p>{{ comment.content }}</p> <div class="rely-button"> <button type="button" name="button" class="reply-btn btn btn-outline-dark btn-sm" id="reply-button">Reply</button> </div> <br> <!-- display replies to the comment --> {# reply per comment #} {# all replies to comments will be shown below the comment #} {% if comment.replies %} {% for reply in comment.replies.all %} <div class="media-replies pull-right"> <div class="media-left"> <img class="media-object" src="{{ reply.profile_picture.url }}" alt=""> </div> <div class="media-body"> <div class="media-heading"> <h4>{{ reply.user }}</h4> <span class="time">{{ reply.timestamp }}</span> … -
DateTimeField saving in local time and not UTC
In my project I have a time_zone attribute using pytz that a user manually sets when creating their account. I also have a form that creates a lesson object, and in that has lesson_datetime, which a user inputs for their desired date and time. Although I have USE_TZ = True and TIME_ZONE = 'UTC' in my settings.py, the database ignores the users time_zone and stores lesson_datetime in their local time as opposed to UTC. I am wondering how to have the form save the lesson_datetime to the database in UTC. I was under the assumption that django did that automatically. I would greatly appreciate any help with this. User model TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones)) time_zone = models.CharField(max_length=100, blank=True, null=True, choices=TIMEZONES) Lesson model class Lesson(models.Model): user = models.ForeignKey(User, null=True, default=None, related_name='lessons', on_delete=models.CASCADE) lesson_instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) lesson_level = models.CharField(max_length=255, choices=level_list, blank=True) lesson_length = models.CharField(max_length=255, choices=length_list, blank=True) lesson_datetime = models.DateTimeField(null=True, blank=True) lesson_weekly = models.BooleanField(default=False, blank=True) views.py def new_lesson(request): if request.method == 'POST': form = LessonForm(request.POST) if form.is_valid(): lessons = form.save(commit=False) lessons.user = request.user lessons.save() messages.success(request,'Lesson successfully created') return redirect('/teacher/schedule') else: messages.error(request, 'Information entered was invalid') else: form = LessonForm() form = LessonForm() lessons = Lesson.objects.filter(user=request.user) context = {'form' : form, 'lessons': … -
Django combine two models instances into one instance for viewing
I am attempting to combine two different (but similar) model instances into one object to work with for viewing purposes. This is a very basic example of what I am trying to do (but for a more complicated model with many properties/functions): class Purchase(models.Model): user = models.ForeignKey(User) amount = models.DecimalField(...) timestamp = ... @property def taxes() ... return tax_amount Now say we have 2 purchases made by the same user. I want to combine those two instances so that in the user view it looks like there is only one instance, but it is really the sum of the two models. This includes the sum of model fields as well as any summable properties. I am not sure what would happen with functions on the model that aren't numerical (but I am okay if they just don't work for the combined instance). -
How to use pathlib.Path in Django?
I'm using pathlib.Path as an alternative to os.path, and I'm trying to use it for the directory paths in the django project, but how much do I try to create migrations, the error occurs: "return database_name == ': memory:' or 'mode = memory' in database_name TypeError: argument of type 'PosixPath' is not iterable " And my base dir: BASE_DIR = Path(__file__).parent.parent.parent Database join: BASE_DIR.joinpath('db.sqlite3') -
django pagination in templateview?
django pagination in templateview? Hello, i try to figure out how i can access multiple models in a Class View and paginate at the same time. My Outcome after reading, DjangoDoc and Stackoverflow: ListView - i simply can use paginate_by= but i can load only one Model TemplateView - i can load many models but can not use paginate_by= ? For example three Models Chicken, Cows and Cats ( and i want to display on my page the last 3 entries of each model. All Models have a model field called entry date. class HomeIndex(TemplateView): template_name = 'home.html' paginate_by = 3 # --- somehting like that def get_context_data(self, **kwargs): context = super(HomeIndex, self).get_context_data(**kwargs) context['chickens'] = Chicken.objects.order_by('-entry_date'') context['cows'] = Cows.objects.order_by('-entry_date'') context['cats'] = Cats.objects.order_by('-entry_date') return context Or maybe i can add something to objects.order_by('-entry_date', < pagination? >) Thanks -
How to move filtred data rows from table to another one using model
I have two model classes A and B and I want to move somme rows from table A to B, I wonder how to do it properly. # models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=200) class A(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) class B(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) #views.py from models import A, B def move(request): filtered_a = A.objects.filter(category=2) """ Here I want to move filtered_a rows to B table, and how to deal with the id """ Please I don't talk about migration, it's treatment that comes after click action, any clean and fast way to do it are welcome. Thank you by advance. -
How to solve faulty Django makemigrations in production
Right now I'm in development so frequently make changes to models, edit, delete, etc. However often even with makemigrations and migrate Django doesn't pick up on the changes I've made. Sometimes running python manage.py migrate --run-syncdb will solve it (yes I know this has been depreciated but it still works which is why I use it as a last resort) but sometimes it doesn't and I have to delete the sqlite database and migrate from scratch. Obviously in production this not going to be possible and I'd like to know the best way to deal with this. -
which version of package do I need to not upgrade django
I was asked to fix an old installation of a Django App I was going through the package dependencies and saw that during a server change they probably lost some python modules: Installed is: Python 2.7.5 and Django (1.8) pip 8.1.2 I need to install django-mptt-admin but I get this error when doing pip install django-mptt-admin: ... Collecting Django>=1.11 (from django-mptt->django-mptt-admin==0.5.8) Using cached https://files.pythonhosted.org/packages/7e/ae/29c28f6afddae0e305326078f31372f03d7f2e6d6210c9963843196ce67e/Django-2.1.7.tar.gz Complete output from command python setup.py egg_info: ========================== Unsupported Python version ========================== This version of Django requires Python 3.5, but you're trying to install it on Python 2.7. the question is now: How can I find the right version of django-mptt-admin and save myself the problem of upragding all python, django and their dependencies? Its a non documented app which probably has some more problems in it In tried pip install django-mptt-admin==0.2.1 (from 0.5.8 down to 0.2.1) but always with the same error. -
Wagtail Stremfield
I wanted to add streamfield to my existing wagtail page for showing ads or news feeds on the vertical side banner. How can I integrate new streamfiled page to existing wagtail page? I am using Django on my backend side. -
DRF: Serializer for heterogneous list of related models
Roughly said, I have the following schema in ORM: class Page(models.Model): title = models.CharField(max_length=255, null=False, blank=False) @property def content(self): return [Video.objects.all()[0], Text.objects.all()[0], Video.objects.all()[1]] and I have the following set of classes to support serialization for detailed view: class ContentSerializer(serializers.ListSerializer): class Meta: model = ??? fields = '???' class PageDetailSerializer(serializers.ModelSerializer): content = ContentSerializer(many=True) class Meta: model = Page fields = ('title', 'content', ) So I'm looking for a way to serialize that Page.content property - which is: a list; will contain heterogeneous data (combination of, let's say Video, Audio, Text and other models. So I need somehow patch one of builtin serializers to iterate thru the list and check type of each object. And then decide how to serialize each one. E.g. I could prepare kind of dynamically created ModelSerializer with: obj_type = type(obj) class ContentModelSerializer(serializers.ModelSerializer): class Meta: model = obj_type fields = '__all__' serialized_obj = ContentModelSerializer(obj) How could I implement that? -
Django forms: display label next to field instead of above it
I'm using {{ form.as_p }} to show my form, it ends with displaying: Label: ||||||||||||||||||||||| what I would like to see is: Label: ||||||||||||||||||||||| Is there a way to accomplish that with CSS or Django? -
message.success not showing message django
I'm new to django, I have been trying to display success message when an user successfully adds an project.I'm using message.success but it doesn't seem to work.I have used the same thing in my other apps but there it works don't know why it doesn't work in this case. Views.py: from django.shortcuts import render from django import views from .forms import project_form from django.shortcuts import render,redirect,HttpResponse from apps.profiles.models import profiles from django.contrib import messages class Add_project(views.View): def get(self,request,*args,**kwargs): loggeduser=profiles.objects.get(Username__username=request.user) return render( request, 'form.html', context={ 'form': project_form(initial={"by_username":loggeduser}) } ) def post(self,request,*args,**kwargs): form=project_form(request.POST) if form.is_valid(): form.save() messages.success(request,('Project saved successfully')) return redirect('projects:AddProject') # projects.objects.get(by_username__username=request.user) else: return HttpResponse( ''' <html><body><h1>Not valid''' ) form.html <html> <body> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{error}} {{ form }} {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}">{{ message }}</li> {% endfor %} </ul> {% endif %} <br> <br> <input type="submit" value="Submit"> </form> </body> </html> urls.py from django.urls import path from .views import Add_project,project_list urlpatterns = [ path('addproject/',Add_project.as_view(),name='AddProject'), ] When redirected the page displays form perfectly but the message doesn't appear.Help me out please. -
Chrome won't load Django default page, everything else is fine
I have a very strange problem. I just installed Django and created a new Project and ran the Django development server. Everything appears fine: Django consoles recieves the GET request, Chrome is loading at 127.0.0.1:8000 but it just stucks there and won't load the page. Only when I stop the development server it loads the page. I tried making the GET request with Postman and Postman did indeed recieve the html, so I think the problem is on Chrome. I tried clearing the cache and everything, running in incognito mode, to no avail. I tried running it with Firefox, same problem. I can't figure out what the problem is. -
How to select None in autocomplete_fields with FK
I've been happily using autocomplete_fields in Django's admin, with M2M, many times and it has worked as expected. Problem happens when using autocomplete_fields for a FK relation. Once a reference value is selected, it seems there is no way to go back to None. I have just edit/add/del symbols as seen on this image: Game FK looks like this: game = models.ForeignKey(Game, default=None, null=True, on_delete=models.PROTECT) Did I miss something, or a workaround should be used, any ideas? -
django-oscar Sandbox project Release version
Is there a "release" version for the sandbox tutorial project? In the have to clone the github repo for django-oscar and make make sandbox from there but can you just build this project independently? -
Forbidden (403) CSRF verification failed. Request aborted. django 2.1
So trying to launch my first django app, it is a simple Morphological Analyzer page that get a japanese sentence from a form and then goes to another page with the results,but im getting this error Forbidden (403) CSRF verification failed. Request aborted as i try to send the form. My template: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>日本語の構文解析</title> <link rel="stylesheet" type="text/css" href="{% static'bunseki/style.css' %}"> </head> <body> <div class="header"> <h1>日本語の構文解析</h1> </div> <div class="sidebar"> このサイトは形態素解析器JUMANを使用し、文を形態素(Morpheme)単位に分割する。 </div> <div class="main"> <div class="bun"> <form method="post"> <h1>解析したい文<h1><br> {% csrf_token %} {{ form }} <br> <button type="submit">解析</button> </form> </div> <div class="footer"> My view: def index(request): form = KaisekiForm(request.POST or None) if request.method == 'POST': if form.is_valid(): request.session['kaiseki_bun'] = request.POST['kaiseki_bun'] return redirect('kaiseki') return render(request, 'bunseki/index.html', {'form': form}) -
Load data in database without refreshing web page
What is the best way or the best programming language or tool to use if i want to load data from web page in a database without refreshing the page ? -
Pass Response (File) From Django to JavaScript
I am trying to achieve the following: Create a file in Django/Python (for instance a Word Document with the python-docx module) Pass the response (the complete file) to JavaScript, so I can do other stuff with this (for instance with the Office Javascript API) I am not sure, whether this is possible (I have only seen ways to pass simple JSON files), but I would love some help. I am now able to create the file and download this to the client's desktop. Then the client has to go through its desktop in order to search for the file and upload it, so JavaScript can work with it (through FileReader). Ideally, I would like to directly send the file to Javascript without all the unnecessary steps. My code: In template.html: # To download the created file from Django/Python <input type="button" value="Download" onclick="window.open('filemaker/download_my_file', '_self')"> # To select the file, so Javascript can use it <input type='file' id='test'> In template.js: $(document).ready(function () { // The document is ready $('#test').change(insertFile); }); function insertFile(){ var myFile = document.getElementById("test"); var reader = new FileReader(); reader.onload = function (event) { // some JavaScript Stuff }; reader.readAsDataURL(myFile.files[0]); } In urls.py: urlpatterns = [ path('/download_my_file', views.create_file_function), ] In … -
How do I access the next token of the url in django template?
In one of my template, I'm trying to access the next token or the name of the view I'm supposed to go to if I were logged. Is it possible to access this information within the template ? -
Join a GenericRelation and limit the result to latest in django
Ok, tricky django query question... I have a model to store emails which is connected (via a generic relation) to several other models (i.e. Participate). I do that, because in my application i send out many emails which are associated to different models and want to have them in one place (the email model). class Participate(models.Model): name = models.CharField(max_length=200) mails = GenericRelation(Email) class Email(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() created_at = models.DateTimeField(auto_now_add=True) message = models.TextField(null=False, blank=False) Now i want to query all datasets from Participate with the latest Email joint if there is one. In SQL (database is postgres) this would look like: select * from participate left join ( select distinct on (object_id) * from email WHERE email.content_type_id=26 order by object_id, created_at desc ) as most_recent_invitation on most_recent_invitation.object_id = participate.id This works fine with the latest email joined if there is one. |----------------|------------------|----------|------------------| | Participate.id | Participate.name | Email.id | Email.created_at | |----------------|------------------|----------|------------------| | 1 | name1 | 1 | 2019-02-20 | |----------------|------------------|----------|------------------| | 2 | name2 | 3 | 2019-02-18 | |----------------|------------------|----------|------------------| | 3 | name3 | | | |----------------|------------------|----------|------------------| | 4 | name4 | | | |----------------|------------------|----------|------------------| However i don't know how … -
Django Crispy Forms - Checkbox not being displayed
I'm trying to add a boolean field on my form and render it with crispy forms tags. And everything is showed except for the checkbox. My project works with django 2.1, python 3.6 and Bootstrap-4. My version of Django Crispy Forms is: 1.7.2 The field is investment. Model field not working: investment = models.BooleanField(default=False, help_text='Want to accept Investments?') My form: class CreateProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'short_description', 'category', 'investment') widgets = { 'name': forms.TextInput(attrs={'placeholder': 'enter the project name here...'}), 'short_description': forms.Textarea(attrs={'rows': '2', 'maxlength': '135', 'class': 'textarea-limited', 'placeholder': 'enter a short description of your project limited to 135 characters'}), } def __init__(self, *args, **kwargs): # first call parent's constructor super(CreateProjectForm, self).__init__(*args, **kwargs) # there's a `fields` property now self.fields['investment'].required = True self.fields['investment'].widget = forms.CheckboxInput() self.fields['name'].widget = forms.TextInput( attrs={'placeholder': 'enter the project name here...'}) self.fields['short_description'].widget = forms.Textarea( attrs={'rows': '2', 'maxlength': '135', 'class': 'textarea-limited', 'placeholder': 'enter a short description of your project limited to 135 characters'}) # evade all labels and help text to appear when using "as_crispy_tag" self.helper = FormHelper(self) self.helper.form_show_labels = False self.helper._help_text_inline = True My View: class ProjectCreateView(SuccessMessageMixin, generic.CreateView): template_name = 'webplatform/project_create_form.html' model = Project form_class = CreateProjectForm success_message = 'Project created! Now try to add … -
Parametrize filtering manager queryset in Django
I want to implement kind of row level security for my model in Django. I want to filter out data as low as it's possible based on some requirement. Now, I know I could create specified managers for this model as docs says but it seems for me that it needs to be static. I also know that I can create just method that will retrurn queryset as I want but I'll be not sufficient, I mean the possibility to just get all data is still there and the simplest mistake can lead to leak of them. So I found this post but as author said - it's not safe nor pretty to mess around with global states. This post is nearly 10 years old so I hope that maybe someone has come up with a beeter generic solution. Here is piece of example to visualise what I need: models.py: class A(models.Model): ... class B(models.Model): user = models.ForeignKey(User) a = models.ForeignKey(A) And I want to create global functionality for getting objects of A only if instance of B with user as logged in user exists. I came up with solution to just override get_queryset() of A manager like so: managers.py …