Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieving unique values from queryset in Django?
I have a fairly straightforward issue I have three models: class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Publisher(models.Model): name = models.CharField(max_length=300) class Book(models.Model): authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) The user can filter books and selects a filter for Publisher-A now I want to update the displayed filters for authors - not showing all authors but only the ones that that published a book with the selected publisher. So I need to retrieve a list of unique authors from the queryset, I suppose. I found this post - but it seems a like a hack to me. Isn't there a standard solution for this? The problem seems so straightforward. Thanks. -
Django Model Overriding save method
This is my models: class Mess(models.Model): alias = models.UUIDField( primary_key=True, default=uuid4, editable=False ) name = models.CharField(max_length=50, null=False, blank=False) address = models.CharField(max_length=300) admin = models.OneToOneField( Person, on_delete=models.CASCADE, related_name='mess_admin' ) members = models.ManyToManyField( Person, related_name='mess_members', blank=True, ) def seve(self, *arg, **kwargs): print(kwargs) I am trying to achive when a new mess created, the members field should be filled with admin. You may notice, the members field is ManyManyToManyField, I want whenver a new mess is creatd, the admin of the mess also will be a members of Mess by default I know i can achieve it with signals but i dont want with it. i wnat to achive it overriding save method. I want members default value will be admin. members = models.ManyToManyField( Person, related_name='mess_members', default=self.admin, blank=True, ) But it not works!!!! can anyone help to achive this? -
Django: Insert or update database entries
I created the following function where I either create a new database entry or update it if event_pk already exists. Now I looked into update_or_create. However, that doesn't work in my case, as the other entries (yhat, etc.) always differ. Do you have any better idea to write it so I don't repeat myself as I do now? One more idea I had was that I could maybe save event=event_obj, yhat=event_forecast.get('yhat') etc. in a dict and unpack it. But didn't figure out how that could work. def insert_forecast_data_to_db(self) -> None: """Insert or update forecast data in database.""" forecast_data = self.get_forecast_data() for event_pk, event_forecast in forecast_data.items(): event_obj = Event.objects.get(pk=event) forecast_obj = Forecast.objects.filter(event=event_pk) if forecast_obj.exists(): forecast_obj.update( event=event_obj, yhat=event_forecast.get('yhat'), yhat_lower=event_forecast.get('yhat_lower'), yhat_upper=event_forecast.get('yhat_upper'), img_key=event_forecast.get('img_key'), ) else: Forecast.objects.create( event=event_obj, yhat=event_forecast.get('yhat'), yhat_lower=event_forecast.get('yhat_lower'), yhat_upper=event_forecast.get('yhat_upper'), img_key=event_forecast.get('img_key'), ) -
How can I send data from the get_avatar() (Google Sign In) to my template?
I have integrated Google Sign In using social_django app although in order to get the profile photo / avatar of the user I have used get_avatar through django pipeline. Now the problem is that how can I send the url received in the get_avatar function to one of my templates? I have tried using Render, HTTPResponse, HTTPResponseRedirect, JSONResponse but I'm not getting the desired results. get_avatar(): def get_avatar(backend, strategy, details, response, user=None, *args, **kwargs): if backend.name == 'google-oauth2': try: url = response["picture"] except KeyError: url = response['image'].get('url') The rendering of get_avatar function returns a empty dictionary to the template. Rather it should return the URL which we get from get_avatar function. Thanks in advance :) -
How to combine validation with select_for_update?
I am developing a billing/banking system. There are 2 models Account and Transaction. On Transaction creationg I want to validate that transaction amount < account balance. I use django-admin and DRF. In both cases user should see validation error messages. In current implementation user sees respones code 500. Is there better way to validate transaction after lock rows? class Account(models.Model): balance = models.DecimalField(max_digits=10, decimal_places=2, default=0) datetime = models.DateTimeField(auto_now=True) class Transaction(models.Model): src = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="out_transactions") dst = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="in_transactions") amount = models.DecimalField(max_digits=10, decimal_places=2) datetime = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): with transaction.atomic(): Account.objects.select_for_update().filter(pk__in=[self.src.id, self.dst.id]) if self.src.balance < self.amount: raise ValueError('Not enough balance') self.src.balance -= self.amount self.dst.balance += self.amount self.src.save() self.dst.save() super().save(*args, **kwargs) -
How to manage user permissions correctly in django?
I have a model called Organization and in the db there are only permissions add_organization, view_organization ,delete_organization,change_organization but I have so many other functions also like filter_org,detail_org and so on.For this how can I set my permissions. Is there any idea to use my urls name instead of permission codename in the permission_required decorator? OR I should be create new permission code and name.But when I used this method ,I think there can be one problem that if the admin added the permission codename for the function org_details to some name like view_organization_detail or something different from the codename which is specified here @permission_required('organization.org_details') then there will be a problem. So what would be the best thing for managing permissions for the functions ? urls.py path('<slug>/detail/', views.org_detail, name='org_details'), views.py @permission_required('organization.org_details', raise_exception=True) def org_detail(request, slug): org = get_object_or_404(Organization, slug=slug) return render(request, 'organization/view_org_detail.html', {'org': org}) -
How does value of query.connector set in Q objects in Django code?
During django websie development I came across of django Q objects & query. I have below code like. I have referred official documentation from https://docs.djangoproject.com/en/2.2/topics/db/queries/. query = Q() if request.POST.get('emp_name') != None: query.add(Q(emp_name__icontains=str(request.POST.get('emp_name'))), query.connector) I know how Query Q objects works but not able to understand how query.connector value defined. query.connector value will be like 'AND' , 'OR' likewise. I am not able to get any online references for above kind of problem. -
how to make collapse in card bootstrap open the content related to each card?
I have a django project that includes cards where each card contains a collapse that will hide or show the data. Problem is once i do a foreach loop the cards appear but the collapse is not working and doesn't display any data. I used the below steps: create function in views.py def displaydata(request,pk): c = cursor.execute('SELECT ID,Nickname_,Date_of_Birth FROM Person_ WHERE ID = pk ') print("c ===>",c) return redirect("search") return render(request,"displaydata.html",{"c":c}) create URL in urls.py path("displaydata/<int:pk>/",displaydata,name = "displaydata") create a template that display the cards <h5 class="card-header"> <a class="collapsed d-block" data-toggle="collapse" href="{% url 'displaydata' pk=obj.0 %}" aria-expanded="true" data-target = "#table-collapsed" caller-id ="" aria-controls="collapse-collapsed" id="heading-collapsed{{obj.0}"> <i class="fa fa-chevron-down pull-right"></i> Details <script type="text/javascript"> $(document).on('click','.collapsed d-block',function(){ $('#heading-collapsed').attr('caller-id',$(this).attr('id')); }); </script> </a> create a template that display the collapsed data <div class="container"> <div class="row justify-content-center"> {% for obj in object_list %} <div class="col-xs-12 col-sm-6 col-md-6 col-lg-4 col-xl-3 mb-5"> <div class="p-2 my-flex-item"> <div class="card innercardzoom"> <div class="inner"> <img src="{% static '/img/card/1.png'%}" class="card-img-top" alt="..."> </div> <h5 class="card-header"> <a class="collapsed d-block" data-toggle="collapse" href="{% url 'displaydata' pk=obj.0 %}" aria-expanded="true" data-target = "#table-collapsed" caller-id ="" aria-controls="collapse-collapsed" id="heading-collapsed{{obj.0}"> <i class="fa fa-chevron-down pull-right"></i> تفاصيل <script type="text/javascript"> $(document).on('click','.collapsed d-block',function(){ $('#heading-collapsed').attr('caller-id',$(this).attr('id')); }); </script> </a> -
Django and Celery 4 test
I read this but not be able to understand. My skills are limited. I had tried several answers from stackoverflow, but they are not work for Celery4 that I am using. I have tasks.py with pn_list in it @shared_task def pn_list(user_ids: typing.List[int], title, msg, extra: typing.Dict = None): ... When I call this function in serializer I have to call with pn_list.delay(...). This comes to be problem. Attempt: I had set my CELERY_TASK_ALWAYS_EAGER=True and CELERY_TASK_EAGER_PROPAGATES=True settings.py. This work in Celery3, but my version is 4 Error: File "/Users/sarit/mein-codes/multy_herr/multy_herr/tweets/api/serializers.py", line 208, in create pn_list.delay(tmp_ids, title, msg, notification_msg) File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.7/site-packages/celery/app/task.py", line 427, in delay return self.apply_async(args, kwargs) File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.7/site-packages/celery/app/task.py", line 552, in apply_async link=link, link_error=link_error, **options) File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.7/site-packages/celery/app/task.py", line 772, in apply propagate=throw, app=self._get_app(), File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.7/site-packages/celery/app/trace.py", line 295, in build_tracer backend = task.backend File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.7/site-packages/celery/app/task.py", line 1030, in backend return self.app.backend File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.7/site-packages/kombu/utils/objects.py", line 44, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.7/site-packages/celery/app/base.py", line 1207, in backend return self._get_backend() File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.7/site-packages/celery/app/base.py", line 925, in _get_backend self.loader) File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.7/site-packages/celery/app/backends.py", line 74, in by_url return by_name(backend, loader), url File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.7/site-packages/celery/app/backends.py", line 54, in by_name cls = symbol_by_name(backend, aliases) File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.7/site-packages/kombu/utils/imports.py", line 57, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "/Users/sarit/.pyenv/versions/3.7.3/lib/python3.7/importlib/__init__.py", line 127, … -
How to set image field as optional?
How to set image field as optional? I am trying to set image field as optional(None or selected). Image field is None its throwing "MultiValueDictKeyError" when submit the form. I want to make this image field as None. models.py class Profile(models.Model): first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) image = models.ImageField(upload_to='images', blank=True, null=True) forms.py class Meta: model = Profile fields = '__all__' views.py def profile(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') image = request.FILES['images'] file_storage = FileSystemStorage() obj = Profile(first_name=first_name, last_name=last_name, image=file_storage.save(image.name, image)) return render(request, 'index.html',{}) return render(request, 'index.html',{}) return render(request, 'index.html',{}) index.html <form action="#" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="first_name" class="form-control form-control" id="fname"> <input type="text" name="last_name" class="form-control form-control" id="lname"> <input type="file" name="images" class="form-control" id="image"> <button type="submit" class="btn btn-primary mt-5 mb-5">Save</button> </form> -
Is There A Way to Query Demographic Sourced from Birthdays?
I am trying to generate demographic data. I made all separate queries because I could not think of the way to do them at once. from django.utils import timezone from dateutil.relativedelta import relativedelta # $ pip install python-dateutil teenagers_count = queryset.filter(birthday__lte=now-relativedelta(years=10), birthday__gt=now-relativedelta(years=20)).count() twenties_count = queryset.filter(birthday__lte=now-relativedelta(years=20), birthday__gt=now-relativedelta(years=30)).count() thirties_count = queryset.filter(birthday__lte=now-relativedelta(years=30), birthday__gt=now-relativedelta(years=40)).count() forties_count = queryset.filter(birthday__lte=now-relativedelta(years=40), birthday__gt=now-relativedelta(years=50)).count() fifties_and_older_count = queryset.filter(birthday__lte=now-relativedelta(years=50)).count() Is there a way to do this by just one query? -
Django many to many field default
I am trying to set the default value of many to many fields. this is my models: class Mess(models.Model): alias = models.UUIDField( primary_key=True, default=uuid4, editable=False ) name = models.CharField(max_length=50, null=False, blank=False) address = models.CharField(max_length=300) admin = models.OneToOneField( Person, on_delete=models.CASCADE, related_name='mess_admin' ) members = models.ManyToManyField( Person, default=admin, related_name='mess_members' ) I am trying to make when there is not members filled, so the default member will be admin for this, i set default=admin but it does not work, when i try to create a mess without filling members field from admin templates, yet it returns me erros: `This field is required. Can anyone help me to set default value in manytomayfield? -
How to get current URL outside views function in django
I want to get the current url outside the view function so that I can have restriction to use a decorator at a specific URL @cache_page(CACHE_TTL) def patients(request): baseContext = BaseContext(header="Dieter") return baseContext.render(request, "patients/patients.html") Now I want to use this "@cache_page" decorator when URL is "https://example.com" How can I to that? -
float() argument must be a string or a number, not 'NoneType'
I want to round a float number, to get 2 digits after point. But I am receiving the error, which is in title class Story(models.Model): ... @property def average_rating(self): return round(float(self.rating_set.all().aggregate(Avg('rating'))['rating__avg']), 2) class Rating(models.Model): rating = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(10.0)]) story = models.ForeignKey(Story, on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) Rounding in rating field of Rating model is a bad idea, because average_rating will not round -
How can I prevent infinite scrolling problem in a web page
I developed a web page with Django and HTML The problem is that after a few post requests from my website, the scroll behaves oddly. As in picture below, if I scroll up then it keep moving upper direction without limits. Similarly if I scroll down then it goes to lower page than the actual foot page. Does anyone know how it occurs and how to prevent it? (If I scroll up ... the white space is the blank space in a web page) -
AttributeError: 'ModelFormOptions' object has no attribute 'private_fields' error message
I don't understand what this error means. It appears that I did everything correctly. from django import forms from django.forms import ModelForm from .models import SignUpForm class SignUpForm(forms.ModelForm): class Meta: model = SignUpForm fields = ['name', 'company', 'city', 'country', 'email', 'password'] widgets = { 'password': forms.PasswordInput(), } This will return AttributeError: 'ModelFormOptions' object has no attribute 'private_fields' This is in my forms.py file. -
Django find item in queryset and get next
I'm trying to take an object, look up a queryset, find the item in that queryset, and find the next one. @property def next_object_url(self): contacts = Model.objects.filter(owner=self.owner).order_by('-date') place_in_query = list(contacts.values_list('id', flat=True)).index(self.id) next_contact = contacts[place_in_query + 1] When I add this to the model and run it, here's what I get for each variable for one instance. CURRENT = Current Object NEXT = Next Object contacts.count = 1114 self.id = 3533 #This is CURRENT.id place_in_query = 36 contacts[place_in_query] = NEXT next_contact = CURRENT What am i missing / what dumb mistake am i making? -
Django Filtering System with django-filter - Filter Queryset
forms.py class SearchFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') language = django_filters.ModelMultipleChoiceFilter(queryset=Language_list.objects.all(),widget=forms.CheckboxSelectMultiple) cast = django_filters.ModelMultipleChoiceFilter(queryset=Cast_list.objects.all(),widget=forms.CheckboxSelectMultiple) class Meta: model = Movies_list fields=['name','language','cast'] views.py def Search_list(request): movies_list = Movies_list.objects.all() movies_filter_complete = SearchFilter(request.GET, queryset=movies_list).qs print(movies_filter_complete) paginator = Paginator(movies_filter_complete, 2) page = request.GET.get('page') movies_filter = paginator.get_page(page) print(movies_filter.has_next()) print(movies_filter) return render(request, 'movies_list/search_details.html', {'filter': movies_filter,"movies_filter_complete":movies_filter_complete}) It work just fine without any error i just want to how can i print custom filter option on template. <form method="get"> <div class="form-group col-sm-8 col-md-6"> {{ filter.language.label_tag }} <div> {% for choice in filter.language %} <label class="checkbox-inline"> {{ choice.tag }} {{ choice.choice_label }} </label> {% endfor %} </div> </div> <button type="submit">Search</button> </form> How can i run this form. -
how to create file upload progress bar in django?
I am trying to create a video blog where users will be able to upload their videos. I have created view and form to upload the file, and also customized the HTML5 video player followint some tutorials. Now I want add a file uploading progress bar but I can't do it for the shortage of my knowledge in programming. I am trying for the last few days. I have found some very old answers on Stackoverflow but they are very difficult for me to understand. I do not want to use any bootstrap framework because my full demo site has been built without any 3rd party framework. I am using Python 3.6, Django 2.2.5, Postgresql 11 on Ubuntu 18.04. Guys could you please see my codes bellow and help me with the easiest way to solve the problem? Thanks in advance! Here is the post form: {% extends 'base.html' %} {% block content %} <!-- GRID SYTEM BEGINS --> <main id="content" class="main-area"> <section class="detail-main-content"> <div class="all-account"> <h1>Create a new post</h1> <!-- form action should be blank always --> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">POST</button> </form> </div> </section> </main> {% endblock content %} Here is … -
model.save() working in some Django views and not others
I am calling save() after making changes to a model, but it is not updating in my database. My save() function for my model isn't broken as it is working sometimes, but other times it isn't working. In the code below, on visiting a URL, it calls the home function, which then calls then the myPage function. def home(request): profile = CustomUser.objects.filter(email='example@example.com')[0] profile.counter = 1 profile.save() myPage(request) def myPage(request): print('Here!') profile = CustomUser.objects.filter(email='example@example.com')[0] profile.counter = 2 profile.save() ... return(request, 'page.html') The myPage function is reached successfully and is printing to my terminal, however the database is only updating to 1 and not 2 as intended. The save function isn't doing anything within the myPage function. What is happening here? -
Django AJAX multiple forms submission
I am submitting a Django form with AJAX. After successful form submission, I am adding saved content to HTML with an option to remove. I am using same AJAX to code to remove the content from database and also from the HTML page. First part is working but when I call java script to remove the content, it's not working. Here is the form submission: <form class='my-ajax-form' method="post" action='.' data-url ='{% url 'update_Tiers' %}' > {% csrf_token %} {% bootstrap_form form %} <button class='btn btn-default' type='submit'>Add</button> </form> Here is the AJAX code: <script type='text/javascript'> count = 0; $(document).ready(function(){ var $myForm = $('.my-ajax-form') $myForm.submit(function(event){ count ++; event.preventDefault() var $formData = $(this).serialize() if ($formData.includes("tier_value")){ var $thisURL = $myForm.attr('data-url') || window.location.href // or set your own url $.ajax({ method: "POST", url: $thisURL, data: $formData, success: handleFormSuccess, error: handleFormError, }) } else if ($formData.includes("post_id")) { // Call to remove the tier view } function handleFormSuccess(data, textStatus, jqXHR){ const div = document.createElement('div'); div.className = 'row'; div.innerHTML = ` <li id='`+count.toString()+`' class="list-group-item"> <b>`+data.name+`</b> <p>`+data.value+`per month</p> <p>`+data.tier_benefits+`.</p> <form class='my-ajax-form' method="post" action='.' > {% csrf_token %} <input id="post_slug" type="hidden" name="post_slug" value=`+data.slug+`/> <input id="post_id" type="hidden" name="post_id" value=`+count.toString()+`/> <button class='btn btn-default' type='submit'>Remove</button> </form> </li>`; document.getElementById('content').appendChild(div); $myForm[0].reset(); } function handleFormError(jqXHR, textStatus, … -
Safe check of invalid data in ModelChoiceField - Django 1.11
I have a codebase I'm trying to migrate from Django 1.8 to 1.11. Yeah, I'm behind the times. Python 3.X and Django 2.X will be a later step. In doing the migration, my tests are showing that where in Django 1.8, sending truly invalid data to a ModelChoiceField used to generate an error on the field, and then a form that returns to it's initial state - now in Django 1.11 the same input causes the form to throw a DataError. For example - if the ModelChoiceField is giving the id of a given model (an integer) and you POST input that is a string, you'll get something like: E DataError: invalid input syntax for integer: "bad role" E LINE 1: ...me" = '') AND "gbe_profile"."workeritem_ptr_id" = 'bad role'... for a form that looks like: ''' from django.forms import ( CharField, ModelForm, HiddenInput, ModelChoiceField, ) from gbe.models import StaffArea from tinymce.widgets import TinyMCE from gbe.forms.common_queries import visible_profiles class StaffAreaForm(ModelForm): required_css_class = 'required' error_css_class = 'error' description = CharField( widget=TinyMCE(attrs={'cols': 80, 'rows': 20})) staff_lead = ModelChoiceField( queryset=visible_profiles, required=False) class Meta: model = StaffArea fields = '__all__' widgets = {'conference': HiddenInput()} ''' And a model that has a typical default primary key … -
Change Django Databse schema in View
How can I change the database schema from django code like views.py I want the user to select a database field type -
Naming results of queryset
The Django ORM provides the Queryset API for filtering records from tables. I want to make queries which can be given a name and then referenced from the resulting filtered queryset I currently have to make two separate queries and then merge them into a single dictionary with keys representing the names I wish to use. # My proposed or desired query statement result = SomeModel.objects.filter(models.Q(source_id=self.pk) as source_record | models.Q(target_id=self.pk) as target_record) # My available option res1 = SomeModel.objects.filter(source_id=self.pk) res2 = SomeModel.objects.filter(target_id=self.pk) result = {'source_record': res1, 'target_record': res2} I have searched the Django model documentation and cannot seem to find any solution to this need. Option 1 does not run and I wish to have a more concise and effective way of making such queries. -
How do I configure VSCode to put template directives in html on separate lines?
I want this: </li> {% endif %} {% if user.messages %} <li To be this: </li> {% endif %} {% if user.messages %} <li I can't find a formatter for django-html, but I'm fine without it. I'd just prefer that those directives go on separate lines.