Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Queryset in template
So the thing is I have this Django ORM QuerySet to get all the Projects and their respective xpm and I just can't figure out why it won't output any of the xpmNumber in the template. xpms = Project.objects.values(ProjectName=F('description'), xPM=F('p_set__flexPMNumber')) I also got this other function to retrieve the same thing but using arawquery: def get_pms(): with connection.cursor() as cursor: cursor.execute('SELECT p.Id, f.Id, p.description AS ProjectName, f.xPMNumber AS xPM FROM ' 'project_project p LEFT OUTER JOIN xpm_pm f ON f.ProjectID = p.Id') xpms = cursor.fetchall() return xpms xpms = get_pms() And this is the template code where I'm trying to render it <div class = "list-group"> {% for f in flexpms %} <a href="" class="list-group-item list-group-item-action"> <p>{{ f.description }}</p> </a> {% endfor %} </div> I've tried with {{ f.projectId.xpmNumber }} to iterate over the first queryset but I get nothing back, I did check that the database has info in those tables and it does. I've also tried to retrieve all the xpms and then use the projectId foreign key like this: xpms = xPMs.objects.all() and iterate over it like this: { % for f in xpms %} {{ f.projectId.description }} {{ f.xPMNumber }} How do I render those xPMNumbers … -
How do translate django template parts?
I've some templates for header and footer html on my templates folder on the root of my project, but the translation is not working with the .mo file, it looks like the translation only occurs on "simple" words like "Home" but the words that i've translated in .po files does not show up. settings: MIDDLEWARES = { # ... 'django.middleware.common.CommonMiddleware', 'django.middleware.locale.LocaleMiddleware', # ... } USE_I18N = True LANGUAGE_CODE = 'en' On my templates/header.html: {% load i18n %} <h1>{% trans "Home" %}</h1> <h1>{% trans "RESOURCES" %}</h1> The locale file on locale/pt-br/LC_MESSAGES #: templates/homepage-navbar.html:21 msgid "RESOURCES" msgstr "RECURSOS" #: templates/homepage-navbar.html:18 msgid "Home" msgstr "Inicio" The template slice is imported on the package example/templates/example/index.html {% include 'homepage-navbar.html' %} But the template only translate "Home" to Início (it's not even what i translate) and it does not translate RESOURCES -
remove orphaned file from a model
I have the following model: class Class(models.Model): title = models.CharField(max_length = 60) video = models.FileField( upload_to = class_files_custom_upload, validators = [ FileExtensionValidator(['mp4', 'webm', 'mpg', 'mpeg', 'ogv']), ] ) section = models.ForeignKey(Section, on_delete = models.CASCADE) created = models.DateTimeField(auto_now_add = True) class Meta: verbose_name = 'clase' verbose_name_plural = 'clases' ordering = ['created'] def __str__(self): return self.title I create an instance of this model, but if I update the video field with another file of any instance, the previous saved file is orphaned and the file takes up space and I want to avoid it, deleting the file. To do this I customize the file load, putting a callable in the upload_to: def class_files_custom_upload(instance, filename): try: old_instance = Class.objects.get(id = instance.id) old_instance.video.delete() except Class.DoesNotExist: pass return os.path.join('courses/videos', generate_secure_filename(filename)) In this way I achieve my goal. But I have several models that save multimedia files, and for each one I have to customize the file load, practically doing a function almost equal to class_files_custom_upload, and the code repeats and this is not optimal at all. I tried to create a reusable function that meets the goal of the class_files_custom_upload function, in various fields like ImageField and FileField, but I can't do it since the … -
Only one field in a Django ModelForm widgets is working
I have a ModelForm wherein the Meta class I say which fields I want and then try to edit the widgets for all of those fields but only the first field is actually working, when I go to the inspector only the first field has the modifications. Forms code: class UserSignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text="Please insert a valid email") class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': forms.TextInput(attrs={'id': 'signup_username', 'placeholder': 'Username'}), 'email': forms.EmailInput(attrs={'id': 'signup_email', 'placeholder': 'Email'}), 'password1': forms.PasswordInput(attrs={'id': 'signup_password1', 'placeholder': 'Password'}), 'password2': forms.PasswordInput(attrs={'id': 'signup_password2', 'placeholder': 'Repeat Password'}) } Template Code: {% for field in signupForm %} {{ field }} {% endfor %} Inspector Code: <input type="text" name="username" id="signup_username" placeholder="Username" maxlength="150" autofocus required> <input type="email" name="email" maxlength="254" required id="id_email"> <input type="password" name="password1" autocomplete="new-password" required id="id_password1"> <input type="password" name="password2" autocomplete="new-password" required id="id_password2"> What am I doing wrong here? -
Django filter based on field of latest related model
I have a model Post and Comment and i'm trying to filter a list of posts to only show the ones that have a certain boolean value (here called epic_bool) on the latest comment. I am trying it as follows: object_list = Post.objects.all() newest = Comment.objects.filter( post=OuterRef('pk') ).order_by('-upload_date') Post.objects.annotate( is_true=Subquery(newest.values('epic_bool')[:1]) ) object_list = object_list.filter(is_true=True) But I get FieldError Cannot resolve keyword 'is_true' into field. Choices are: ... I don't understand why because i'm trying to annotate and not resolve a field!? -
error: 'ValueError: _names_ are reserved for future Enum use'
I'm deploying my Django project on a Linux server. When I run the command python manage.py collectstaticI get the following error: File "/home/student/PickFeel/venv/lib/python3.5/site-packages/django/db/models/enums.py", line 81, in TextChoices def _generate_next_value_(name, start, count, last_values): File "/usr/lib/python3.5/enum.py", line 61, in __setitem__ raise ValueError('_names_ are reserved for future Enum use') ValueError: _names_ are reserved for future Enum use enum.py is a system generated file. How do I fix this? -
Django TestCase and Transactions
I am running into a weird issue while writing unit tests that I think is related to this from the django docs - Django's TestCase class wraps each test in a transaction and rolls back that transaction after each test, in order to provide test isolation. This means that no transaction is ever actually committed, thus your on_commit() callbacks will never be run. My issue is occuring when working with update_fields in save(). Some pseudo code for example. object.is_processing = timezone.now() object.save(update_fields=['updated', 'is_processing']) try: with transaction.atomic(): # do stuff object.other_field = value object.save() finally: object.is_processing = None object.save(update_fields=['updated', 'is_processing']) Now when I run tests, it tries to create the object twice. Why? I think it is because this is all in a transaction, so the object is never actually committed to the database. When I call save with update_fields the pk is excluded, so it looks at it like a new object, and tries creating it twice. If I do the following, it works. object.is_processing = timezone.now() object.save() try: with transaction.atomic(): # do stuff object.other_field = value object.save() finally: object.is_processing = None object.save() What I am trying to figure out is how to test this without changing the production code … -
get host address heroku django API
I have deployed a react-django app on heroku.... The react front end makes calls to the django backend. However, django backend isn't accepting the requests..I'm guessing that it's either 1) wrong host address or 2) server didn't start... if it's wrong host address(' i used '127.0.0.1' as host address in all urls for get and post in react), how do i get the right one, else if server didn't start, how do i get it to start, else kindly point out the problem and the solution. What is the problem? Thanks to anyone trying to help : ) -
why this basic like implementation isn't working?
I'm making a simple like button but it's not working and I get the error database is locked and that's because sqlite can't handle it but I want to make a simple like button and if sqlite can't handle it then it's not simple. this is the like model: class Like(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) imageid = models.CharField(max_length=50) and this is the view: @login_required def like(request, imageid, action): username = request.user im = get_object_or_404(Images, imageid=imageid) likecount = Like.objects.filter(imageid=imageid).filter(username=username).count() if likecount == 0: l = Like(username = username, imageid= imageid) l.save() if action == 'vote': im.vote = F('vote') + 1 im.save() else: return redirect('home') else: print("already liked") how can I make this work? thanks -
Django list view order by alternating supplier
I have a django ListView which queries for products. I now have a new supplier and I get feeds from each supplier at different times of the day. Whenever one supplier updates I get all the updated products from SUPPLIER_A first and then when SUPPLIER_B updates I get all them returning first. This is pushing each supplier off the first few pages so no user will ever see them products for part of the day. How do I alternate by supplier e.g. my products on page 1 will have 12 from each supplier. class Product(models.Model): SUPPLIER_A = "A" SUPPLIER_B = "B" SUPPLIER_CHOICES = ((SUPPLIER_A,SUPPLIER_A), (SUPPLIER_B, SUPPLIER_B)) category = models.ForeignKey(Category, on_delete=models.PROTECT) supplier = models.CharField(choices=SUPPLIER_CHOICES, max_length=20) class ProductListView(ListView): template_name = "product_list.html" paginate_by = 24 def get_queryset(self, *args, **kwargs): slug = self.kwargs.get("slug") return models.Product.objects.filter(category__slug=slug) -
Static File location on Django app deployed to Google App Engine / Cloud SDK
I have developed a website using the latest version of Django, finished all the offline testing, and deployed it to Google App engine. Previously, images and scripts for my website were located in a folder titled ‘scripts’, and running locally I had no problems. Now that my website is deployed however, no images / scripts / static files are successfully loading, and I cannot figure out an appropriate fix. I have successfully created a bucket with google cloud, but I can’t seem to create a functioning path to that bucket. I am unsure whether a html address is a valid parameter for the path location in Settings.py, and regardless replacing the simple HTML address of my google cloud bucket for my STATIC_URL parameter has not fixed the problem. Has anybody else run into this problem, and does anyone know the best configuration for the static_url parameter in Settings.py? Or a simpler way to set up your static files? Thanks in advance! -
How to run same set of test for anonymous user and logged in user?
I have a simple MovieDB app written in Django where webpages differ slightly between logged in view and guest user view. I have a movies list page which doesn't change for logged in user and anonymous user except for sign-in/register links to sign-out. I am currently testing template used, no. of movies listed, movie title, nav-bar links (home, search page, login/register, sign-out, user account). I want to write tests to check these for both type of user only once. -
How to access static file from a template tag in Django to read a text file?
I am building a system where I want to read a text file from my template. This text file is stored in my static folder. In my app_filters, I have the following function: from django import template register = template.Library() @register.filter def print_file_content(file_name): try: file = open(file_name, 'r') return file.read() except IOError: return '' On my template, I am doing this: {% load static %} {% load app_filters %} <div>{{ "{% static 'my_file.txt' %}" | print_file_content }}</div> I have the file in my static folder: myapp/static/my_file.txt, but the file is not read correctly. And the section just remains empty. How can I fix this issue? Thanks for any help. -
python docxtpl - cant create dynamic form
I have been trying to create a dynamic table in word but the created file has all the contents except the list inside the options tag. I have tried a lot of stuff but can't get it to work. from docxtpl import DocxTemplate from registration.models import stuff def create_doc(options, model, file='resources/stuff.docx'): doc = DocxTemplate(file) log = stuff(options_object=model) log.save() l = [] for i in range(1, len(options) + 1): x = {} x['number'] = i x['course'] = options[i - 1] l.append(x) context = { 'name': model.name, 'reg_no': model.regno, 'roll_no': model.rollno, 'rank': model.student_rank, 'course': model.alloted_to, 'cat': model.alloted_cat, 'options': l } doc.render(context) doc.save(f'media/request_{model.rollno}.docx') The template The output -
I am having unbelievably hard time understanding two scoops of Django, What should I do? [closed]
I have read Django tutorials and practiced Django for a while now and even have made my blog project using Django but still I am having unbelievably hard time understanding two scoops of Django if at all I am understanding anything, What should I do? Is it normal or am I missing some link? -
Reorganizing ManyToMany models into a different order
I have an setup similar to this. class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) books = models.ManyToManyField(Book) def __unicode__(self): return self.title class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author) def __unicode__(self): return self.title Now in my admin panel I can select an author and add Books underneath that specific author. When I print out all the books for each author it prints them in the order that they were added in the admin panel. Is it possible to modify the order in the admin panel so that when they print, they print in the order of the admin panel? -
GeoDjango prevent save latitude and longitude field
i had created longitude and latitude field on my admin, but when i use draw marker instead of input long/lat field, my empty value long/lat field save override my pointfield. Do you have solution for it ? Thank you for reading my question and sorry for my english is bad. model.py class Hostels(models.Model): osm_id = models.CharField(max_length=10) code = models.IntegerField(null=True) fclass = models.CharField(max_length=28) name = models.CharField(max_length=100, default='') address = models.CharField(max_length=100, default='') image_upload = models.ImageField(upload_to='image_nhatro', null=True, blank=True) price = MoneyField(max_digits=14, decimal_places=2, default_currency='VND', default='0') created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) area = models.FloatField(blank=True, null=True) description = models.TextField(blank=True, null=True) room = models.IntegerField(blank=True, null=True) people = models.IntegerField(blank=True, null=True) phone = models.IntegerField(blank=True, null=True) name_contact = models.CharField(max_length=100, default='') mail = models.CharField(max_length=100, default='') geom = models.PointField(srid=4326, blank=True) def __unicode__(self): return self.name form.py class HostelAdminForm(forms.ModelForm): latitude = forms.FloatField(min_value=-90, max_value=90, required = False) longitude = forms.FloatField(min_value=-180, max_value=180, required = False) class Meta(object): model = Hostels exclude = [] def save(self, commit=True): self.instance.geom = Point(self.cleaned_data["longitude"], self.cleaned_data["latitude"]) return super(HostelAdminForm, self).save(commit) admin.py class quanly_nha_tro(LeafletGeoAdmin): list_display = ('name', 'created_at', 'updated_at') exclude = ('fclass','osm_id','code') form = HostelAdminForm my img admin -
How to make the images same fit or same size?
I'm developing an e-commerce project in django, I have created a model for images and tried to resize or thumbnail the images but it seems this is not working for my case or maybe this is Front-end issue. When the vendor uploads the image products, I want the image products to fit and look in the same line regardless of the image original size. I don't want them to show like in this picture so I want the price and button to be in the same line. I tried to resize the images but won't work -
Make Django 3 REST render HTML template
I am trying to build a Django (version 3.05) REST API call that will render to a chosen HTML template. I am, however, receiving a number of errors that I haven't found a solution to on StackOverflow (And yes, I've looked far and wide). Since my errors are many and varying depending on what I attempt, let me rather ask how to do it correctly to begin with. In my view set up (below), what do I need to add (or change) in order to render the queryset to an HTML template? models.py: from django.db import models class Hero(models.Model): name = models.CharField(max_length=60) alias = models.CharField(max_length=60) def __str__(self): return self.name serializers.py: from rest_framework import serializers from .models import Hero class HeroSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Hero fields = ('name', 'alias') views.py: from rest_framework import viewsets from .serializers import HeroSerializer from .models import Hero class HeroViewSet(viewsets.ModelViewSet): queryset = Hero.objects.all().order_by('name') serializer_class = HeroSerializer # over here - how do I render the queryset /to/my/template.html myapi/urls.py: from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'heroes', views.HeroViewSet) -
Django error 'model' object is not iterable
Good afternoon, I am following a Django tutorial to lean and I came up with an TypeError at /x/ I am not sure what I am doing wrong here is the model class articulos(models.Model): nombre = models.CharField(max_length=30) seccion = models.CharField(max_length=30) precio = models.IntegerField() here are the views from django.shortcuts import render from django.http import HttpResponse from GestionPedido.models import articulos def buscar(request): if request.GET["prd"]: #mensaje = "Artículo buscado: %r" %request.GET["prd"] producto = request.GET["prd"] articulo = articulos.objects.filter(nombre__icontains = producto) return render(request, "resultadobusqueda.html", {"articulos":articulos, "query":producto}) else: mensaje = "No has introducido nada %r" return HttpResponse(mensaje) and here is the temple <html> <body> <p>Estas buscando: <strong>{{query}}</strong></p> {% if articulos %} <p>Articulos encomtrados {{articulos|length}} articulos</p> <ul> {% for articulo in articulos %} <li> {{articulos.nombre}} </li> {% endfor %} </ul>> {% else %} <p>Articulos no encontrado</p> {% endif %} </body> </html> it does mark the error {% for articulo in articulos %} I had some other errors that I have manage to find but this one is driving me crazy. I am still learning and finding it all very interesting. Thank you very much! -
Does anyone have an idea how can I set up a specific subscription in stripe with such a special requirements for upgrading and downgrading?
I am working on a platform able to analyse data of the users. I would like to use Stripe payments however I have some problems. At first I would like to describe how I would like my pricing look like in order to make it clearer to understand for you what I want to achieve. During account creation the user can select an amount for example from 1$ to 1000$ that will be available for all services. This amount will be charged every month so this will be working as a subscription plan. The difference is that the amount is not used proportionally each day of the month, as is the case of subscriptions. For example, the user starts one month pricing period 5th of the month with amount equals to 10$. During first 10 days of this period he does not execute any actions so he still has 10$. On the 11th day, he starts the service and uses 4$ within 5 hours. From this time he does not use any tools until the end of the current period and he has 6$ left. I decided at the moment that unused funds will probably not be transferred to the … -
Like Button simultaneously working on all instances at the same time when clicked Jquery, Ajax
i am new to Jquery and Django, I have a problem with the like button, I changed all the id's to classes but now when liking one post, all the like buttons on all posts in the list are getting triggered at the sametime. When using ID, only the 1st instance is working. Is there a way to sort out this issue? js. $(document).ready(function(event){ $(document).on('click', '.like-btn', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: pk, data: {'csrfmiddlewaretoken': '{{ csrf_token }}'}, datatype: 'json', success: function(response){ $('.like_snippet').html(response['form']) console.log($('.like_snippet').html(response['form'])); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); like snippet.html <form action="{% url 'posts:like_post' post.slug %}" method="post">{% csrf_token %} {% if is_liked %} <button type="submit" id="like" name="post_slug" value="{% url 'posts:like_post' post.slug %}" class="like-btn btn-sm btn-outline-danger">{{ post.likes.count}} Unlike{{ post.likes.count|pluralize }}</button> {% else %} <button type="submit" id="like" name="post_slug" value="{% url 'posts:like_post' post.slug %}" class="like-btn btn-sm btn-outline-info">{{ post.likes.count}} Like{{ post.likes.count|pluralize }}</button> {% endif %} this is the snippet in the homepage and the tag <div id="like-snip" class="like_snippet"> {% include 'posts/like_snippet.html' %} </div> Is there a way to make this work? I tried changing ID's and classes but still it doesn't work. Thanks in advance! -
WYSIWYG with images uploader, how to upload images after writing in the wysiwyg
I'm writing an application where a user can write a diary, also the user can add images, so I'm using the input file to choose images and un put inside the content editable. After the images are in the content editable, I can see the html as img base 64. So, I was thinking if is possible to upload images after the user submitted everything? or should I upload the images via Ajax and put inside the editor with the right url. (I only think that this option people can upload images than delete from the editor and these images will be kept inside the server useless.) Thank you for any response! -
I got an API on AWS how to post json data using django?
It is working fine when I pass data from POSTMAN. I just want to call the API from Django the same as we do in the postman. -
Merge two Different fields result django Query
I have a model from which I want to get data in a same object(JSON) I have this model class Suggestion(models.Model): city = models.CharField(max_length=250 , null=True , blank=True) name = models.CharField(max_length=250 , null=True , blank=True) Now I will query like this name = Suggestion.objects.filter(name__icontains=search) city = Suggestion.objects.filter(city__icontains=search) Name=nameSeilizerr(activities,many=True) serializer=CitySeilizer(city,many=True) In serializer I will send only name in Nameserializer and city in city Serilizer. Main Concept is I want to suggestion to user either its Name or city name in field. Any help would be highly appreciated.