Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Sum values for loop in template
I have this template that is a search engine. I need all the searched items to be added, but as i did it sums up all the database items. and I need it to show only the sum of the searched items. sum all loop items {{images.price | mul:images.pictures}} views.py def search(request): sales_list = Images.objects.all() sales_filter = ImagesFilter(request.GET, queryset=sales_list) places_count = Images.objects.all().annotate(total=Sum('pictures')) return render(request, 'paneladmin/sales_list.html', {'filter': sales_filter, 'places_count': places_count}) filter.py class ImagesFilter(django_filters.FilterSet): checkin = django_filters.NumberFilter(widget=DatePickerInput(format='%d'),field_name='checkin', lookup_expr='day' ) checkin1 = django_filters.NumberFilter(widget=DatePickerInput(format='%m'),field_name='checkin', lookup_expr='month' ) checkin2 = django_filters.NumberFilter(widget=DatePickerInput(format='%Y'),field_name='checkin', lookup_expr='year' ) # usando o name__photographers eu estou dizendo que quero busca o name da tabela photographes, desse modo terei um boxlistt em meu template name__photographers = django_filters.CharFilter(lookup_expr='icontains', field_name='name') class Meta: model = Images fields = ['name', 'checkin'] sales_list.html {% load mathfilters %} {% for images in filter.qs %} {{images.price | mul:images.pictures}} {{ places_count }} {% endfor %} -
How to use Python Keyring from Django without user interaction?
I need to store some third party server passwords in Django, in views.py to be more specific. Those are used for Paramiko SFTP (machine-to-machine communication) and it's not possible to use keys instead of passwords. For sure I don't like to write those passwords directly to source code. I have figured out that Python Keyring would be good way to store passwords and following short code works ok: import keyring try: keyring.get_keyring() keyring.set_password("system", "user", "passWORD") pword = keyring.get_password("system", "user") print pword except Exception as e: print e I moved the code to Django (views.py): from django.http import HttpResponse import keyring def index(request): try: keyring.get_keyring() keyring.set_password("system", "user", "passWORD") pword = keyring.get_password("system", "user") return HttpResponse(pword) except Exception as e: return HttpResponse(e) Then I asked Django to run built-in development server by typing: sudo python manage.py runserver Finally I browsed to correct localhost url. Result: browser was showing dialog requesting me to create (on first try) and then open (on next tries after I have created it) kdewallet. Is it possible to use Keyring from Django without need for user interaction (= without those dialogs)? -
How to remove a field from modelform model instance?
I have a question related this one: How to handle the validation of the model form when the model has a clean method if the model form excluded some fields? This is my model: class StudentIelts(Model): SCORE_CHOICES = [(float(i/2), float(i/2)) for i in range(0, 19)] IELTS_TYPE_CHOICES = [('General', 'General'), ('Academic', 'Academic'), ] student = OneToOneField(Student, on_delete=CASCADE) has_ielts = BooleanField(default=False, ) ielts_listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_overall = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_exam_type = CharField(max_length=10, null=True, blank=True, choices=IELTS_TYPE_CHOICES, ) ielts_exam_date = DateField(null=True, blank=True, ) ielts_file = FileField(upload_to=student_directory_path, null=True, blank=True, ) student_ielts_non_empty_fields = \ { 'ielts_listening': 'please enter your listening score', 'ielts_reading': 'please enter your reading score', 'ielts_writing': 'please enter your writing score', 'ielts_speaking': 'please enter your speaking score', 'ielts_overall': 'please enter your overall score', 'ielts_exam_type': 'please enter your exam type', 'ielts_exam_date': 'please specify your exam date', } def clean(self): errors = {} if self.has_ielts: for field_name, field_error in self.student_ielts_non_empty_fields.items(): if getattr(self, field_name) is None: errors[field_name] = field_error if errors: raise ValidationError(errors) class StudentIeltsFilterForm(ModelForm): class Meta: model = StudentIelts fields = ['has_ielts', 'ielts_listening', 'ielts_reading', 'ielts_writing', 'ielts_speaking', 'ielts_overall', 'ielts_exam_type', ] def __init__(self, *args, **kwargs): … -
objects.create(...) does not create the objects
For some reason my objects aren't being created: def upload_view(request): key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}' for file in request.FILES.getlist('fileToUpload'): TemporaryImage.objects.create(image=file, key=key) return HttpResponse('complete') TemporaryImage.objects.all() returns an empty QuerySet, and when I inspect the database, nothing is there, yet I can see the HttpResponse being returned successfully. I don't see any errors. The same is true when I do: tmp_img = TemporaryImage(...) tmp_img.save() What could be the cause? -
How to view local webpage in iframe of public webpage?
I've been working on a security camera project where I have a raspberry pi that hosts a local webpage with the live video feed from its camera. I also have a server running at home whitch hosts a public webpage. I want to be able to view the local webpage from the raspberry pi from the public webpage. Is there a way I can use an Iframe or something to view the local webpage from everywhere from within the public webpage? -
Django Users Default Profile Image not showing
I am trying to add set the default profile picture for the users who doesn't add their profile. I am following this tutorial but for some reason default picture isn't showing up on the profile tab. I have mentioned all the code I can below but click here to check complete code. About Project There are two apps blog and users along with main project directory django_project. Click here to check complete code. But main profile.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src='{{ user.profile.image.url }}'> <div class="media-body"> <h2 class="account-heading">{{user.username}}</h2> <p class="text-secondary">{{user.email}}</p> </div> </div> <!-- FORM HERE --> </div> {% endblock content %}` admin.py from .models import Profile from django.contrib import admin admin.site.register(Profile) apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] models.py from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") def __str__(self): return f"{self.user.username} Profile" views.py from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm from django.shortcuts import … -
How to add more data when registering a user by python-social-auth
I already implemented a successful Facebook register form in my django project with python-social-auth. However, now I need to create the registered user with additional data in the register form of my page. I mean allowing to retrieve the necessary data from Facebook to create the new user, but also use the data from the form (the user could fill this data before or after redirecting to Facebook, but that is not my concern here). How can it be done in general terms? -
How to monkey patch django function?
I want to customize django admin change_list_result row content, so i guess override related to change_list_result function. And I found to konw call display_for_field via items_for_result in django.contrib.admin.templatetags.admin_list. admin_list.py I put following code to the manage.py, but doesn't work. from django.contrib.admin.utils import display_for_field from warehouse.monkey_patching import _display_for_field_mod display_for_field = _display_for_field_mod -
Django - how to store different parsing techniques for different XML formats?
Every user has different csv/xml feed url. Some users feeds are "standardized" so the parsing techniques/scripts can be shared. But some users has very unique feed formats and I need to write custom script. I'm trying to figure out way to store such scripts so either I choose existing parsing technique inside admin or I write code and assign it to the object. How would you do that? My idea is to have a folder with these scripts and every object would have FilePathField so I can choose or create a new script. Is there another way? class Feed(BaseTimeStampedModel): url .... name = models.CharField(max_length=64) template = models.FilePathField(path='feeds/parsers/', recursive=True, match='tparser__.*') -
Class views in Django, Html not showing
Im quite confused with why my html template is not showing up. Im trying to learn Class base views instead of functions on Django. I know the url is working because {% extend base.html %} is showing, but anything else like the h1 tags aren't showing up in the render? Can anyone help please. views.py from django.shortcuts import render from django.views import View from django.views.generic import ( CreateView, DetailView, ListView, UpdateView, ListView, DeleteView ) from .models import Article class ArticleListView(ListView): template_name = 'article/article_list.html' queryset = Article.objects.all() url.py from django.contrib import admin from django.urls import path from .views import ( ArticleListView ) app_name = 'article' urlpatterns = [ path('', ArticleListView.as_view(), name = 'article_list'), article_list.html {%extends 'base.html'%} <h1> Test </h1> <h1> Test </h1> {%block content%} {% for instance in object_list %} <p>{{instance.id}} - <a href = '{{instance.get_absolute_url}}'> {{instance.title}} </a></p> {%endfor%} {%endblock%} -
how to group records by hour and return instances
this is my model and i am using postgresql: class TripRequest(models.Model): passenger = models.ForeignKey('user.Passenger', on_delete=models.DO_NOTHING) beginning_point = models.PointField() destination_point = models.PointField() trip_beginning_time = models.DateTimeField() ... i'm not very familiar with advance orm queries i want to group trip requests that have nearest (for example in a specific hour) beginning time and after that filter it furthermore like nearest beginning point or nearest driver. now there are answers on SO that group the query and return the count or other information of all the group items but i want to just group the instances by hour and have a collection of instances for further filtering how can i do that? -
I am not getting any errors in my terminal yet my contact page doesn't display my email fields
I am not getting any errors in my terminal yet my contact page only displays the header "Contact Form" and a "Send Message" button without the fields required for my form. The fields are (Username, Email, Subject & Content). If i can get my form to display the required fields so that users can enter the required details and post their queries id be happy. Kindly assist and if i have left an important bit kindly tell me and i will update my question. Thanks in advance. MY forms.py file looks like this from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # contact form class ContactForm(forms.Form): contact_username = forms.CharField() contact_email = forms.EmailField() contact_subject = forms.CharField() content = forms.CharField() class Meta: model = User fields = ['contact_username', 'contact_email', 'contact_subject', 'content'] My views.py file looks like this from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm # contact form view def contact(request): Contact_Form = Contact_Form if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_username = request.POST.get('contact_username') contact_email = request.POST.get('contact_email') contact_subject = request.POST.get('contact_subject') contact_content = request.POST.get('content') template = get_template('buyer/contact_form.txt') content = { 'contact_username' : request.POST.get('contact_username'), 'contact_email' : request.POST.get('contact_email'), 'contact_subject' : request.POST.get('contact_subject'), 'contact_content' : request.POST.get('contact_content'), … -
Django Error: "TypeError: join() argument must be str or bytes, not 'Path'" when running manage.py migrate with cookiecutter-django installed
I have been trying to set up Django with a cookiecutter-django project and I'm getting this error output when I run python3 manage.py migrate TypeError: join() argument must be str or bytes, not 'Path' -
How to actually make a PATCH request to DRF
So I've been looking around and researching a bit and still couldn't figure out how to make a PATCH request to the DRF. Here's my view: class AttendanceView(viewsets.ModelViewSet): queryset = Attendance.objects.all() serializer_class = AttendanceSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) parser_classes = (MultiPartParser, FormParser) def patch(self, request, *args, **kwargs): att = self.request.query_params.get('id', None) att_obj = get_object_or_404(Attendance, pk=att) serializer = AttendanceSerializer(att_obj, data=request.data, partial=True) if serializer.is_valid(): att_obj = serializer.save() return Response(AttendanceSerializer(att_obj).data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def post(self, request, *args, **kwargs): file_serializer = AttendanceSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) And I have all the standard serializers and urls set. I am using the Python requests library. How do I send a PATCH request to my API so I can update a field in my attendance object? Also please let me know if there's something missing in or for my patch method. I appreciate your time in reading this. Thank you so much. -
Django caching (?) HTML
I'm using Django==2.2.6 (haven't kept up with the later releases, I don't know what's new) and it seems like it is caching my html-files, somehow? Currently, at the index-page is says: SHISH There are NO references to "SHISH" in the code, whatsoever. -
AttributeError: 'bytes' object has no attribute '_committed'
I have a form with an <input type="file">, and I'm getting an error when I try to save the uploaded image. The image is uploaded via POST XMLHttpRequest. I have no idea why this is happening. views.py: import datetime from django.shortcuts import render from .models import TemporaryImage def upload_file(request): key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}' for file in request.FILES.get('file'): img = TemporaryImage(image=file, key=key) img.save() def home_view(request): return render(request, 'products/home.html', {}) models.py: from django.db import models def get_temp_image_path(instance, filename): return os.path.join('tmp', str(instance.id), filename) class TemporaryImage(models.Model): image = models.ImageField(upload_to=get_temp_image_path, blank=True, null=True) key = models.CharField(max_length=100) urls.py: from django.contrib import admin from django.urls import path from products.views import upload_file, home_view urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('upload/', upload_file, name='upload_file') ] template 'home.html': <!DOCTYPE html> <html> <head> <title>SO Question</title> <script> function uploadFile() { var fd = new FormData(); fd.append("file", document.getElementById('file').files[0]); var value = []; document.getElementsByName('csrfmiddlewaretoken').forEach(function(x) { value.push(x.value); }) fd.append('csrfmiddlewaretoken', value[0]); var xhr = new XMLHttpRequest(); xhr.open("POST", '/upload/'); xhr.send(fd); } </script> </head> <body> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} <label for="file">Select a File to Upload</label> <input type="file" id="file" name="file"> <input type="button" onclick="uploadFile()" value="Upload"> </form> </body> </html> full stack trace: [06/Oct/2019 12:05:40] "GET / HTTP/1.1" 200 968 request.FILES is <MultiValueDict: {'file': [<TemporaryUploadedFile: 20190615_193154.jpg (image/jpeg)>]}> image is b'\xff\xd8\xff\xe1\\\xd5Exif\x00\x00II*\x00\x08\x00\x00\x00\x0c\x00\x00\x01\x04\x00\x01\x00\x00\x00 \x10\x00\x00\x01\x01\x04\x00\x01\x00\x00\x00\x18\x0c\x00\x00\x0f\x01\x02\x00\x08\x00\x00\x00\xae\x00\x00\x00\x10\x01\x02\x00\n' … -
Why does my Django robots.txt works on development but returns server error 500 on production?
I'm trying to create a robots.txt file for my django website following this tutorial The end result is good on development and everything is working. However, when I pushed the files into production I got a Server Error (500) even though I changed all the 127.0.0.1:8000 into mywebsite's domain. My settings.py Installed apps looks like this: INSTALLED_APPS = [ 'search.apps.SearchConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'robots', 'django.contrib.sites', ] My main project's urls.py looks like this: urlpatterns = [ path('admin/', admin.site.urls), path("", include("search.urls")), path("sitemap.xml", sitemap, {'sitemaps': sitemaps}), path('robots.txt',include('robots.urls')), ] I installed the django-robots using pip install, and I did the necessary migrations on my production server but it doesn't fix the problem. -
Type error str in not callable python3 django models.py
I checked other problems and solutions in stack, but everywhere problem exists in views.py or urls.py like I understood. Now I,ve got only model.. Sorry for my English, but I'm learning now also :( (yes, yes too late) Where is my problem? below I paste traceback and models.py. Is this enough? If I broken every rules on stackoverflow I'm sorry, this is my first post, please correct me. It will be great help for me. Thank for the Help! from django.db import models from django.db.models.fields.related import ForeignKey class DeviceType(models.Model): """Model representing a device type.""" type_device_name = models.CharField(max_length=100) short_name_device= models.CharField(max_length=7, default='Maszyna') who_is_made = models.CharField(max_length=100) additional_notes = models.TextField(max_length=1000, help_text="Type all important information about.") def __str__(self): """String for representing the Model object.""" return f'{self.short_name_device}' class Device(models.Model): """Model representing a device.""" type_name = models.ManyToManyField(DeviceType, help_text='Select a device type') device_id = models.DecimalField(max_digits=4, decimal_places=0) short_name_device_own = ForeignKey(DeviceType, related_name='device_type_device', on_delete=models.SET_NULL, null=True) prod_year = models.DateTimeField(auto_now=False, auto_now_add=False) worked_science = models.DateField(auto_now=False) @property def __str__(self): """String for representing the Model object.""" return f'{self.short_name_device_own}, {self.device_id},' Traceback: File "/home/robert/.local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/robert/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/robert/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/robert/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 606. return self.admin_site.admin_view(view)(*args, **kwargs) File … -
Custom template tag rise error "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet."
I'm tying to create template filter, which will take value and search it in my model import django django.setup() tried this it didn't help Here is my code from catalog import models from django import template, shortcuts register = template.Library() @register.filter(name='test') def test(value): item = shortcuts.get_object_or_404(models.Equipment, pk=value) return item.name And i get this error File "C:\Users\mro\PycharmProjects\EuroWeb\catalog\templatetags\catalog_custom_tags.py", line 1, in <module> from catalog import models File "C:\Users\mro\PycharmProjects\EuroWeb\catalog\models.py", line 4, in <module> class EquipmentCategory(models.Model): and Apps not loaded error File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. whole traceback is to big to post it here -
Why html skips my variable and how can I fix it?
views.py ... def home(request): data = { 'title':'Main page' } ... home.html ... <title>{{ title }}</title> ... browser page => show code ... <title></title> ... Why he just skipped title? It definitely worked in the tutorial. -
How to filter best related and create in one query?
I want to select best related object and save new one in one query to avoid race condition. Is it possible? Does select_for_update solves this problem? class Order(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2, default=0) maker_order = models.OneToOneField('self', on_delete=models.CASCADE, blank=True, null=True, related_name='taker_order') def save(self, *args, **kwargs): self.maker_order = Order.objects.filter(maker_order__isnull=True, taker_order__isnull=True, price__lte=self.price ).order_by('price').first() super().save(*args, **kwargs) -
How correct open connections to database in Python/Django
I want know how open correctly new connection to database. A problem rise when i want create single QUERY to database, from many places in my code. For example, one request is sent to database from login.html , second from register page, third to gallery in index.html . I guess , should i use some project patterns? Do you have some suggestion ? I have written this class which are responsible for connection to mysql database. I suppose that it is very wrong (i don't focus yet on validation - but i know about that): import mysql.connector import configparser class DataBaseConnectionHandler(object): __DATABASE = "" user = "" passwd = "" host = "" fileName = "" dataBaseConnection = "" def __init__(self, fileName=None, host='localhost'): if fileName is not None: config_file = configparser.ConfigParser() config_file.read('shop/config/dbConfig.ini') database: str = config_file.get('DEFAULT', 'database') user: str = config_file.get('DEFAULT', 'user') password: str = config_file.get('DEFAULT', 'password') self.__DATABASE = database self.user = user self.passwd = password self.host = host def connectToDatabase(self): """ EXECUTE CONNECTION AND RETURN AN HOOK TO DATABASE""" dataBaseConnector = mysql.connector.connect( host=self.host, user=self.user, passwd=self.passwd, database=self.__DATABASE ) if dataBaseConnector != "": self.dataBaseConnection = dataBaseConnector return self.dataBaseConnection else: self.dataBaseConnection = None return self.dataBaseConnection from .databses import DataBaseConnection class RegisterUser(object): __formName … -
Set ordering of Apps and models in Django admin dashboard
By default, the Django admin dashboard looks like this for me: I want to change the ordering of models in Profile section, so by using codes from here and here I was able to change the ordering of model names in Django admin dashboard: class MyAdminSite(admin.AdminSite): def get_app_list(self, request): """ Return a sorted list of all the installed apps that have been registered in this site. """ ordering = { "Users": 1, "Permissions": 2, "Activities": 3, } app_dict = self._build_app_dict(request) # a.sort(key=lambda x: b.index(x[0])) # Sort the apps alphabetically. app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower()) # Sort the models alphabetically within each app. for app in app_list: app['models'].sort(key=lambda x: ordering[x['name']]) return app_list mysite = MyAdminSite() admin.site = mysite sites.site = mysite new look and feel: But as you see, I have lost the AUTHENTICATION AND AUTHORIZATION section; What should I do to have all the sections and at the same time have my own custom ordering for Profile section? -
S3 old uploaded image displayed with django-storages - deactivate caching?
When uploading a file I want to overwrite the existing file. I save all files with the same name. The upload to S3 seems to work but the new image is not displayed. I think, this is due to S3 caching making images (saved under the same name) available after 24h? I want to disable that cashing when uploading a new file with boto3 and django-storages but I can't seem to figure out how this works? I the docs I find this parameter, but is does not seem to work: AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } -
Unable to reach Django channels with Apache
I just deployed a Django Project on an Ubuntu server with Apache. Everything worked fine but I am unable to connect to the websocket.. I also enabled Proxy and put ProxyPass into the apache config file but still nothing. What way would be the most efecient? I also have a .app domain that only acceseble through https, so should I use wss in the config file and also to access the WebSocket? And If I run it on the same server as the main Django project in the settings it should be localhost as a server right?