Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In template,I'm passing an object in a loop to show all items in the list
I have created a model object called Store and passed it to a django template and called it in a for loop within a POST form as the following: ` {% csrf_token %} <br/><br/> <br/> <div class="row"> {% for store in stores %} <input type="hidden" name="store_id" value="{{store.id}}"> <input type="submit" value="{{store.store_name}}{{store.id}}" class="button store-button" type="button"> {% endfor %} </div> </form>` It works fine, shows all the buttons with each store name and id on clickinig the button it submits the form and takes me to next template where I have captured the POST store id and student id and passed them to next page template. But the problem is that the store shown is always the last added stor, no matter which button I press in the first page of the POST form, but the buttons show the different stores and their ids perfectly, I can't understand why this is happening as not even an error is shown, please help me, thanks in advance. -
Django queryset. Retrieve only the last 3 created objects for all stores
My platform have a Product and a Store models and I want to retrieve only the last 3 created products for all stores. I don't want to iterate over all queryset as in the future there will be many products and stores. I've tried to get the number of newer products and then filter by 0, 1 and 2: products_queryset.annotate(newer_products=Count(Q(store=F('store')) & Q(created__gt=F('created')))).filter(newer_products__lte=3) With this query I'm always getting newer_products=1, so the filter is returning all products. -
DJANGO - how can I filter an object filtering by another object filtered
I'm trying to make an advanced filter with django objects but I just have no clue of how to do it. I'll try to explain myself: I have 2 objects: Consumptions: class Consumption(LogsMixin, models.Model): """Definición del modelo de Consumos""" STATES = [ ('not-prevalidated', 'No prevalidado'), ('prevalidated', 'Prevalidado'), ('pendant', 'Pendiente validación cliente'), ('accepted', 'Aceptado'), ] client = models.ForeignKey('authentication.Client', verbose_name=("Cliente"), null=True, default=None, on_delete=models.SET_DEFAULT) access_date = models.DateField("Fecha de acceso", auto_now=False, auto_now_add=False) status = models.CharField("Estado", max_length=20, choices=STATES, null=False, blank=False) and Clients class Client(LogsMixin, models.Model): """Model definition for Client.""" company_name = models.CharField("Nombre de la empresa", max_length=150, default="Nombre de empresa", null=False, blank=False) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) And now I want to count all clients that has some consumption in 'pendant' state and in certain date. As you can see consumptions has one client related. I've checked the docs https://docs.djangoproject.com/en/3.1/topics/db/queries/ but I just can't get what I want. Could someone help me? :( -
How to set up Gcloud Flex Environment custom container pylibmc
I am trying to set up memcached for my application. Locally it works just fine. Now time to deploy to a real server, I am using Google cloud app engine flex environment. It's a custom runtime. I am able to install my app just fine, but when it comes time to running, I get a 500 for views that I use Memcached. My first thinking is because of the caches settings: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': '127.0.0.1:11211', } I am thinking it has something to do with this location setting. Being that this '127.0.0.1:11211' works for a local environment, how do I setup a location for gcloud custom runtime flex environment? If that's not why I am getting the 500, what could be the better setup. Here is my docker file: FROM python:3.8 EXPOSE 8080 RUN apt-get update && apt-get install --reinstall -y \ binutils \ libproj-dev \ libmemcached11 \ libmemcachedutil2 \ libmemcached-dev \ libz-dev ADD requirements.txt /app/requirements.txt RUN pip install -r /app/requirements.txt ADD . . # Run a WSGI server to serve the application. gunicorn must be declared as CMD exec gunicorn --bind :8080 --workers 1 --threads 8 main:app --timeout 0 --preload and app.yaml file: runtime: … -
how to download an uploaded file in django
am creating an option to download a file (pdf) uploaded.just through searching i have across with some instruction (a view) and (url) ,when i try to pass the named url to my template i get this error Reverse for 'download' with no arguments not found. 1 pattern(s) tried: ['download/(?P<filepath>[^/]+)/$'] Just i cant figure a way to download the file.what i want to achieve is that once a download button is place should open a new tab and preview the file and give an option to print or download the file(pdf) using the chrome features. here are the codes views.py import os from django.conf import settings from django.http import HttpResponse, Http404 def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 models.py class Cv(models.Model): filename = models.CharField(max_length=20) upload = models.FileField(upload_to='cv') def __str__(self): return self.filename urls.py path('download/<str:filepath>/', views.download, name="download"), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) template <a href="{% url 'download' %}" class="btn btn-fill wow fadeInUp" data-wow-duration="0.8s" data-wow-delay="0.4s">Downlaod <i class="fa fa-download"></i></a> help please -
I am unable to loaddata json into my postgres database
Im trying to do the below command but im getting this long error. I have also tried to do go into the dbshell to trucanate as i saw suggested elsewhere but im getting the error that psql is not install or path found even though it should be. I have been succesful in managing to get my tables in the postgres database but their are all empty except a few, which i find strange. My Json dump file has everything it needs in it but it wont transfer over. Anyone have any ideas? (venv) DEMOPROJECT>python manage.py loaddata "datadump.json" Traceback (most recent call last): File "\PycharmProjects\WebP1\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(admin, logentry) already exists. django.db.utils.IntegrityError: Problem installing fixture '\DEMOPROJECT\datadump.json': Could not load contenttypes.ContentType(pk=1): duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3 d3b_uniq" DETAIL: Key (app_label, model)=(admin, logentry) already exists. -
How to pass javascript variable in ajax django url
<script> $(document).ready(function () { $(window).on('beforeunload', function () { $.ajax({ // type: 'GET', url: "{% url 'size_reducer:data_delete' id %}", dataType: 'json', success: function (data) { console.log('ok'); } }) }); }); </script> I want to pass id in ajax URL but it is giving me an error because it's not getting id -
Group by, annotate and display extra data from parent model in Django REST Framework
I have two models related with a foreign key (employee): class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) site = models.CharField(max_length=100) wage = models.DecimalField(max_digits=4, decimal_places=0, default=0) class Record(models.Model): employee = models.ForeignKey(Employee, related_name='employee', on_delete=models.DO_NOTHING) date = models.DateField() cash = models.DecimalField(max_digits=4, decimal_places=0, default=0) I would like to obtain a JSON aggregation for an employee describing total cash he earned and the date_ranges: { "id": 0, "name": "John Doe", "position": "", "site": "", "total_cash": 1500.0, "start_date": "", "end_date": "" } I would like to filter the results based on a date range in the future, so annotating the Employee objects is not an option. Or am I wrong here? What I've done: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['id', 'name', 'position', 'site', 'wage'] class RecordSerializer(serializers.ModelSerializer): employee__id = serializers.ReadOnlyField(source='employee.id') employee__name = serializers.ReadOnlyField(source='employee.name') start_date = serializers.DateField() end_date = serializers.DateField() total_cash = serializers.FloatField() class Meta: model = Record fields = ['employee__id', 'employee__name', 'total_cash', 'start_date', 'end_date'] In the view I'm overriding the .get_queryset() method class RecordView(viewsets.ModelViewSet): serializer_class = RecordSerializer queryset = Record.objects.all() def get_queryset(self): return Record.objects.values('employee__id', 'employee__name')\ .annotate(total_cash=Sum('cash'), start_date=Min('date'), end_date=Max('date')) I'm getting the right query result, but I cannot get the serializer to recognize the employee__name or employee__id fields. This is the JSON response: … -
How to dynamically exclude a field from Django Model Form
I have a django Form class which is used to post data by a user in a forum. The class is shown below. class PostForm(forms.ModelForm): body = forms.CharField(label=_('Body'), widget=TinyMCE( attrs={'cols': 40, 'rows': 30, 'placeholder': _("Your answer...")}, mce_attrs=TINYMCE_DEFAULT_CONFIG)) class Meta(): model = Post exclude = ('creator', 'updated', 'created', 'topic', 'user_ip', 'telegram_id') The form only includes the body field as of now. I want to be able to dynamically exclude this body field when instantiating a form of this class. I need this because I am trying to use another django app called django-flag-app which is used to flag inappropriate posts by the user. This app adds a field to model of this form. So when a user flags it, it's showing an additional tinymce widget which should not be displayed. I want to prevent this by adding body to excludes dynamically. How can I achieve that ? -
Creating a function to check some combination of checks for auth
I am trying to create a boolean auth function that takes in some combination of *args and **kwargs to enable auth checks. This particular function checks the user's group membership and admin status along with the usual permissions. Note that if a user is admin, they are allowed to bypass the permissions. def auth_check(request, org_group, *perms): if request.user not in User.objects.filter(groups__name__in=[org_group]): return False if request.user.groups.filter(name='admins').exists(): return True for perm in perms: if request.user.has_perm(perm) == False: return False return True My question is how do I make it so it is possible to pass in some or condition for the *perms. For example something like 'model.change_object' | 'model.remove_object' like they do with complex lookups in Django. -
How to provide unique id to the button in a forloop to the single button in django templates?
I am trying to give a unique id to the button by adding post id in the button id, I don't understand how can i call this button id in ajax function. The way i am trying to do is wrong,So when i click on button that returns nothing. postlist template: {% csrf_token %} {% for post in object_list.all %} <div class="cardbox"> <div class="cardbox-heading"> <!-- START dropdown--> <div class="dropdown pull-right"> <button class="btn btn-secondary btn-flat btn-flat-icon" type="button" data-toggle="dropdown" aria-expanded="false"> <em class="fa fa-ellipsis-h"></em> </button> <div class="dropdown-menu dropdown-scale dropdown-menu-right" role="menu" style="position: absolute; transform: translate3d(-136px, 28px, 0px); top: 0px; left: 0px; will-change: transform;"> <a class="dropdown-item" href="#">Hide post</a> <a class="dropdown-item" href="#">Stop following</a> <a class="dropdown-item" href="#">Report</a> </div> </div><!--/ dropdown --> <!-- END dropdown--> <div class="media m-0"> <div class="d-flex mr-3"> <a href="#"><img class="img-responsive img-circle" src="{{post.username.avatar.url}}" alt="User"></a> </div> <div class="media-body"> <p class="m-0">{{post.username}}</p> <small><span>{{post.create_date|timesince}}</span></small> </div> </div><!--/ media --> </div><!--/ cardbox-heading --> <div class="cardbox-item"> <a href="{% url 'posts:post_detail_final' pk=post.pk slug=post.slug %}" data-toggle="modal"> <img class="img-responsive" src="{{post.image_data.url}}" alt="MaterialImg"> </a> </div><!--/ cardbox-item --> <div class="cardbox-base"> <ul> {% for likes in post.likes.all %} <li ><a href="{% url 'profiles:detail' username=likes.username %}"><img src="{{likes.userprofile.avatar.url}}" class="img-responsive img-circle" alt="User"></a></li> {% endfor %} </ul> </div><!--/ cardbox-base --> <div class="cardbox-like"> <ul> <li> <span class="" id="like_count">{{post.likes.count}}</span> <button class="btn btn-link text-dark p-0 border-0 … -
Django rendering a page with a small selection. Should this be faster?
All the code in this example is just a simplified representation. The actual code is more complex, but I believe that for this question this should be sufficient. I am unfortionaly stuck with a very old version of Django, which I can not change: 1.7.1 I render a .html page using django. The html page contains instances of artist. class Artist(EmptyModelBase): name = models.CharField(max_length=127) etc. etc. When a request comes, it goes to views.py where we do this: def some_function(req): # do some stuff filter = # filter actually comes from the request items = Artist.objects.filter(**filter) items = items[0:20] # return max 20 instances, even if we have more context = {'artists':items} return render(req, 'artist.html' , context) The .html itself is relatively simple. It contains more then this, but this is the essence: {% for item in artists %} <p class="artist"> {{ item.name | safe}} </p> {% endfor %} Everything above works as expected. Based on the request, and the filter in the request, there will be anywhere between 1 and 250k instances of Artist returned by the query. I take a slice of max 20 instances, and then render the page. My issue: if the request returns very few … -
Add custom model method in Django admin
I have a model Ad which has a custom add_ownership_including_ancestors method. Like below: models.py class Ad(models.Model): name = models.CharField(max_length=100) creator = models.ForeignKey('User', on_delete=models.CASCADE) def add_ownership_including_ancestors(self, current_user_id): #function to add permissions to current_user and creator and their ancestors views.py class AdViewSet(viewsets.ModelViewSet): def create(): #here the method is called adInstance.add_ownership_including_ancestors(request.user.id) Now this functionality works fine in normal webpage. I want the same method to be implemented in django admin pages whenever I create or update ad object from django admin pages. How can I do that? -
Django Randomly Select List Item to Display In Template
I have a list of strings in a .py file located in the same dir as my working app. I want to display a randomly selected item from the list and have it display in the template of my app. On each refresh of the page i want the random selection to change. I can't work out how this is possible at the moment. I'm thinking two things: run a random selection within the .py that has my list; or bring the entire list into the template and then use JS(?) to randomly select an item. Any advice? -
invalid input syntax for type integer: "1.0"
Having trouble reading csv file in python data frame got error Skipping line 4565: unexpected end of data invalid input syntax for type integer: "1.0" Any suggestions? -
Dictionary as string in django template
I have a dictionary in this format: dict = [{ "key1": "value1" "key2": "value2" "key3": "{"name": "", "age": "", "sex": ""}" }, ] NOTE: key3 is a string holding a dictionary On the template I can actually pull key1, key2, key3 since they are straight forward. But, key3 is one more dictionary stored in string. I'm able to do this: {% for eachObj in dict%} { eachObj.key1 } { eachObj.key3 } <!-- This prints whole dictionary--> { eachObj.key3.name } <!-- This line doesn't work since it is a string --> {%endfor%} Is there some way where I can try doing like: JSON.parse(eachObj.key3) inside that for loop? -
Name is not editing after click on edit button . ( No errorr )
#Forms.py ( I have added the form for edit the user profile ) class CreateForm(forms.ModelForm): Full_name = forms.CharField(required=True) class Meta: model = Profile fields = ('Full_name') #Views.py ( edit_post is the view for edit user profile ) def edit_post(request): args = {} if request.method == 'POST': form = CreateForm(request.POST or None, instance=request.user) form.actual_user = request.user if form.is_valid(): Full_name = request.POST['Full_name'] form.save() return HttpResponseRedirect(reverse('mains:profiles')) else: form = CreateForm() context = {'form':form} return render(request, 'mains/edit_post.html' , context) #Urls.py ( edit_post url is the url of edit user profile ) path('edit_post/', views.edit_post, name='edit_post'), #Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='') Full_name = models.CharField(max_length=40,default='') email = models.EmailField(max_length=60,default='') #Edit_post.html {% extends "mains/base.html" %} {% block content %} <p><a herf="{% url 'mains:profiles' %}">Edit Profile</a> <form action="{% url 'mains:edit_post' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Edit Post"/> </form> {% endblock content %} -
HTML is there a way to limit the year to 4 digits in date input
I am developing a django app. I have date input in my form: <input type="date" name="date_of_birth" class="dateinput form-control" required id="id_date_of_birth"> It allows to enter the date with the year having 6 digits, but I wish it was only possible to enter 4. I tried max, max-length attribute with pattern. I also tried to write a simple script: $(function() { $('#id_date_of_birth').change(function() { var date = $(this).val(); console.log(date, 'change') }); }); but it only starts when I change the year. I would like the numbers to loop on 4 digits instead of 6. Can someone give me a hint how to limit the year to only 4 digits? -
Dynamic sitemap with paginated external content (API) of 1 million data
This question is not specific to my setup but I have a Nextjs app for frontend and Django app for backend. I want to create sitemap but when I fetch data from API it comes in the paginated form as usual. I can adjust the number of items in these API responses but I have ~1 million pages. So what's the approach to generate sitemap for this kind of large sites? -
How to pass selected value from dropdown in Django?
I have a combobox onchange of selection in need to load the field with list of items. I tried various method to pass the selected dropdown value to a method. I tried to call a javascript method in from datalist onChange event but it didn't work. how can we achieve this? I am tried for full day but unfortunately no luck. Model. CATEGORY_CHOICES = Choices( ('KtCoffee', 'Karnataka Coffee'), ('Atea', 'Assam tea'), ('WBRice', 'West Bengal Rice'), ('GujCotton', 'Gujarat Cotton'), ('KerCocoa', 'Kerala Cocoa'), ) class maincategory(models.Model): category = models.CharField(choices=CATEGORY_CHOICES,max_length=25) def __str__(self): return self.category VIEW def update(request): if request.method == "GET": context = { 'choices': maincategory._meta.get_field('category').choices } return render(request, 'update.html', context) HTML <div> <input list="category-input"> <datalist id="category-input" style="width:100px"> {% for des,text in choices %} <option value={{text}}>text</option> {% endfor %} </datalist> </div> -
how to merge my dataframe to models in django?
I am trying to put my dataframe into mysql database in my django project for two days but not able to do this. this is my views.py file from django.shortcuts import render, redirect from .models import App from .forms import AppForm from django.core.files.storage import FileSystemStorage import MySQLdb from pandas.io import sql con = MySQLdb.connect("localhost", "root", "1234", "djstudent" ) def list_app(request): app = App.objects.all() import pandas as pd data = [['tom', 10.0, 5], ['nick', 15.0, 3], ['juli', 14.0, 1]] df = pd.DataFrame(data, columns=['description', 'price', 'quantity']) df.to_sql(App, con=con, if_exists='replace') return render(request, 'app.html', {'app': app}) def create_app(request): form = AppForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return redirect('list_app') return render(request, 'app-form.html', {'form': form}) def update_app(request, id): app = App.objects.get(id=id) form = AppForm(request.POST or None, instance=app) if form.is_valid(): form.save() return redirect('list_app') return render(request, 'app-form.html', {'form': form, 'app': app}) def delete_app(request, id): app = App.objects.get(id=id) if request.method == 'POST': app.delete() return redirect('list_app') return render(request, 'app-delete-confirm.html', {'app': app}) this is my model.py file from django.db import models # Create your models here. class App(models.Model): description = models.CharField(max_length=100) price = models.DecimalField(max_digits=9,decimal_places=2) quantity = models.IntegerField() #media = models.FileField(upload_to='media', default="") def __str__(self): return self.description settingspy Django settings for crud1 project. Generated by 'django-admin startproject' using Django 2.2.2. … -
Why Django is encapsulating all the content inside the Body Tag
I have a problem that I am reproducing with a simple example. No matter what I do I do always have a page with my content inside a body (js, footer, etc) like the image attached. Can anyone help me to figure this out? Thank you. If I remove the body tag from base.html, django include a body tag itself that encapsulates the remaining content. base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> </head> <body> {% block content %} {% endblock content %} </body> <footer> <h3>This is the footer</h3> </footer> <script src="{% static 'js/jquery-3.5.1.min.js' %}"></script> <script src="{% static 'bootstrap-4.4.1/js/bootstrap.min.js' %}" ></script> </html> home.html: {% extends 'base.html' %} {% block content %} <div> <h1>This is the home body</h1> </div> {% endblock content %} The render result: -
Use django filter in FullCalendar.io
I am making a fullcalendar in my Django project, and I want to use django filters to filter the calendar. I have successfully created the calendar and the filters, but I can't get it to work together. This is my latest error when using the filter in combination with the calendar. Does anyone have experience with including django filters (or another filtering approach) in a fullcalendar, or have a link to documentation that explains filtering in fullcalendar? -
Trying to deploy a second app on my linode server
I have an app running on my linode server, but since my app is not being used much and I have enough memory, I decided to host another app on same server but I have been unable to do so, I have tried so many tutorials online but I have not been successful with it. Please assist. Thanks in advance. -
Pagination and queryset
I have a queryset : items = Items.objects.all() category_query = request.POST.get('category) items = items.filter(category = category_query) I have a paginator : from django.core.paginator import Paginator paginator = Paginator(items, 18) page_query = request.GET.get('page') items = paginator.get_page(page_query) when I click on Next in the pagination it remove the active filter on my items. How can I avoid that ?