Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
AttributeError: 'Manager' object has no attribute 'all_with_related_persons_and_score'
File "/home/syed007/PYTHON/myprojects/MyMDB/django/core/views.py", line 60, in MovieDetail queryset = Movie.objects.all_with_related_persons_and_score() AttributeError: 'Manager' object has no attribute 'all_with_related_persons_and_score' I'm using Django 2.2.4 on Python 3.6 when run "python3 manage.py makemigrations core", got the above error then changed the views script and that worked. But we cannot make views. However that created my models. But again, when running the command,"python3 manage.py runserver", got this error -- from django.db import models from django.conf import settings from django.db.models.aggregates import Sum class MovieManager(models.Manager): def all_with_related_persons(self): qs = self.get_queryset() qs = qs.select_related('director') qs = qs.prefetch_related('writers', 'actors') return qs def all_with_related_persons_and_score(self): qs = self.all_with_related_persons() qs = qs.annotate(score=Sum('vote__value')) return qs ` -
Django pre-selected checkbox with forms
I have two dropdown menus that depend on each other. In the first drop-thorn the annual number of maintenance can be selected. In the second dropdown menu the corresponding intervals can be selected. Now I would like to store the actual maintenance months in the database with preselected checkboxes. For this, I have created a table with the entire months of a year and established many too many relationships with the possible intervals. How can I preselect the checkboxes depending on the interval possibilities? I hope it is understandable and thank you for your help. Here is my code: models.py ss Systems(models.Model): systemUUID = models.CharField(max_length=30) idNum = models.CharField( max_length=50) postalcode = models.CharField(max_length=10, blank=True) city = models.CharField(max_length=50, blank=True) street = models.CharField(max_length=150, blank=True) fitter_mailaddress = models.EmailField(blank=True) general_mailaddress = models.EmailField() author = models.ForeignKey(User, on_delete=models.CASCADE) personnel_maintenance_per_year = models.ForeignKey(Personnel_maintenance_per_year, on_delete=models.SET_NULL, null=True) select_the_maintenance_months = models.ForeignKey(Select_the_maintenance_months, on_delete=models.SET_NULL, null=True) jan = models.BooleanField() feb = models.BooleanField() mar = models.BooleanField() apr = models.BooleanField() may = models.BooleanField() jun = models.BooleanField() jul = models.BooleanField() aug = models.BooleanField() sep = models.BooleanField() oct = models.BooleanField() nov = models.BooleanField() dec = models.BooleanField() def __str__(self): return self.systemUUID def get_absolute_url(self): return reverse('systems-detail', kwargs={'pk': self.pk}) form.py (currently not used) class SystemForm(forms.ModelForm): class Meta: model = Systems fields = … -
Django - I need help fixing this NoReverseMatch error
I'm following this tutorial upload multiple images to individual model objects within an object creation form. The main difference between my code and the tutorials is that I've changed the word 'photos' to 'images' for consistency with the rest of my project. Here is my views.py for the Upload form. class CarCreate(CreateView): model = Car fields = '__all__' success_url = reverse_lazy('showroom:car-detail') slug_field = 'id' slug_url_kwarg = 'car_create' def get(self, request): image_list = Car.objects.all() return render(self.request, 'showroom/car_form.html', {'images': image_list}) def post(self, request): form = ImageForm(self.request.POST, self.request.FILES) if form.is_valid(): image = form.save() data = {'is_valid': True, 'name': image.file.name, 'url': image.file.url} else: data = {'is_valid': False} return JsonResponse(data) The relevant template markup: <button type="button" class="btn btn-primary js-upload-photos"> <span class="glyphicon glyphicon-cloud-upload"></span>Upload images </button> <input id="fileupload" type="file" name="file" multiple style="display: none;" data-url="{% url 'showroom:images:image_upload' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> Here is the error raised: Exception Type: NoReverseMatch at /showroom/create/ Exception Value: 'images' is not a registered namespace inside 'showroom' After reading through other Stackoverflow answers, I've tried a few different solutions: 1. It's not a namespacing error since I've already attached the 'showroom:images'. 2. The problem resides within: 'data-url="{% url 'showroom:images:image_upload' %}"' I know because if I change the data-url to '#', the page loads … -
Django rest framework csv renderer doesn't render €(EUR) sign correctly
I am using django-rest-framework-csv(https://github.com/mjumbewu/django-rest-framework-csv/) to download csv from api. Problem is when I write row with € sign, I get it like this in excel: Code: renderer = CSVRenderer() renderer.header = ['last_name', 'first_name', 'nutrition_text', 'monthly_total_price'] renderer.labels = { 'last_name': 'Nachname', 'first_name': 'Vorname', 'nutrition_text': 'Ernährung', 'monthly_total_price': 'Monthly total price' } data = [ {'last_name': 'asdasd', 'first_name': 'asdas', 'nutrition_text': '', 'monthly_total_price': ''}, {'last_name': 'Delic', 'first_name': 'Mirza', 'nutrition_text': '', 'monthly_total_price': '-18.00€'} ] response = HttpResponse(renderer.render(data), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Data.csv"' return response Excel screenshot: Also, Ernährung is not good in excel. Any solution for this?