Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Webpack still showing old code afer changes. How do I reload webpack?
Currently have a django/react app that I am creating. Had some errors on my webpack that I had to change. After doing this I tried loading the site again and for some reason the old code is still showing. Anything I can do to resolve this? Thanks in advance! -
Save master and details in DRF with foreign key
I am trying to save a entity from a request. I have two models class Reservation(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) userReservation = models.ForeignKey(User, on_delete=models.CASCADE, default=1) dateStart = models.DateTimeField(null=False, blank=False, default=datetime.now) def __str__(self): return str(self.id) class DetailsReservation(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Reservation = models.ForeignKey(Reservation, blank=False, on_delete=models.CASCADE, null=True, related_name='reservation_details') product = models.ForeignKey(Product, blank=False, on_delete=models.CASCADE, null=True, related_name='products_reservation') Quantity = models.IntegerField(null=False, blank=False, default=0) def __str__(self): return self.product.product_Description +" by: " + self.userbyReserva.email def save(self, *args, **kwargs): self.userbyReserva = self.Reservation.userReservation super(DetailsReservation, self).save(args, kwargs) Then i have two serializers class DetailsReservationSerializer(serializers.ModelSerializer): class Meta: model = DetailsReservation fields = '__all__' class ReservationSerializer(serializers.ModelSerializer): reservation_details = DetailsReservationSerializer(many=True) class Meta: model = Reservation fields = '__all__' then in my views, i have class makereservation(generics.ListCreateAPIView): def post(self, request, *args, **kwargs): data = request.data data["userReservation"] = request. user.id serializer = ReservationSerializer(data=data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) I am trying with postman (for emulate request type post) this is my json { "dateStart": "2020-09-20T13:00:00-05:00", "reservation_details": [{ "product": 1, "Quantity": 2 }, { "productId": 2, "Quantity": 2 }, { "productId": 3, "Quantity": 1 } ] } but i don't know, how save this. first, i tried to save Reservation, after obtain these is, and with id tried insert DetailsReservation, but … -
Django Rest Framework and @staticmethod. What is the benefit of it?
I was coding some methods in serializers.py usign PyCharm. Then I had to code a method to get a name. def get_artist_name(obj): return obj.artist.name Then PyCharm suggested me to make the method static. @staticmethod def get_artist_name(obj): return obj.artist.name Since then I'm wondering what is benefit of it? It's a good practice or something like that? If there is any documentation I can read about this specific topic, thanks in advance. -
TypeError: expected a character buffer object using .translate in python 2.7
I'm getting the error "TypeError: expected a character buffer object" in the line where it says "words = user_input_txt.translate(translate_table).lower().split(). I checked the type for the argument "user_input_txt" and its . I'm not sure what I'm doing wrong and don't quite understand previous postings. If someone could advise on how to fix I would greatly appreciate! def contains_bad_words(user_input_txt): """ remove punctuation from text and make it case-insensitive""" translate_table = dict((ord(char), None) for char in string.punctuation) words = user_input_txt.translate(translate_table).lower().split() for bad_word in blacklist: for word in words: if word == bad_word: return True return False -
How to add a search for drop down list in admin page when adding a record
I have following model from django.db import models class Ipaddress(models.Model): ipaddress=models.CharField(max_length=20) slug = models.SlugField(unique=True) machinename=models.CharField(max_length=500) user=models.CharField(max_length=200) department= models.ForeignKey('Department',on_delete=models.CASCADE,default='Empty') location= models.ForeignKey('Location', on_delete=models.CASCADE) updated = models.DateField("Date Updated",null=True) note =models.TextField() def __str__(self): return self.ipaddress[:50] In the admin page: from django.contrib import admin from pages.models import Post, Device, DeviceType, DeviceModel, Ipaddress, DeviceGroup, Location,Department,Comment from django_admin_listfilter_dropdown.filters import DropdownFilter, RelatedDropdownFilter class IpaddressAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('ipaddress',)} search_fields = ['ipaddress', ] list_display = ('ipaddress', 'machinename', 'user', 'department','location','updated',) list_filter = ( ('user', DropdownFilter), ('department', RelatedDropdownFilter), ('location', RelatedDropdownFilter), ) When I try to add a device it shows following page: The location list could be few thousands racks. So, i need to type the rack instead of scrolling 1000 of records. Any idea how i can do that. -
Django: How to override unique_together error message on Admin Side?
I need some help to customize this error. Seen already on this site how can i change the error for the Model Form. My issue is that i use purely django admin side and i need to change how the error looks. I've added them also in my Class Meta from the admin.py and nothing happen! When i put this code to my Class Meta in my models i receive this error message TypeError: 'class Meta' got invalid attribute(s): error_messages therefore my question here. Please find below my models: from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from datetime import datetime, timedelta, time from django.core.exceptions import NON_FIELD_ERRORS class Parcare(models.Model): PARKING_PLOT = (('P1', 'Parking #1'), ('P2', 'Parking #2'),('P3', 'Parking #3')) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,null=True, default=1, on_delete=True) email=models.EmailField(blank=True, null=True) parking_on = models.DateField(auto_now=False, auto_now_add=False,blank=True, null=True, help_text='Alege data cand doresti sa vii in office',) parking_off = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, help_text='Alege Data Plecarii') numar_masina = models.CharField(max_length=8, default="IF77WXV",blank=True, null=True, help_text='Introdu Numarul Masinii') location = models.CharField(max_length=3, blank=True, default="P1",null=True, choices=PARKING_PLOT, help_text='Alege Locul de Parcare Dorit') updated = models.DateTimeField(auto_now=True, auto_now_add=False,blank=True, null=True) timestamp=models.DateTimeField(auto_now=False, auto_now_add=True,blank=True, null=True) venire = models.TimeField(default=time(9, 00), auto_now=False,auto_now_add=False, help_text='Alege Ora Venirii') plecare = models.TimeField(default=time(18, 00), auto_now=False, auto_now_add=False, … -
Display one question from a table at a time in quiz application django
I have tried a lot but i am not able to display only 1 question at a time in quiz application django. Here is the body of html file {% csrf_token %} Welcome {{user.username}}, To Online Quiz {% for item in query_results %} {{ item.QUESTION_NO }} {{ item.QUESTION }} {{item.OPTION1}} {{item.OPTION2}} {{item.OPTION3}} {{item.OPTION4}} -
Problem with uploading files to HDFS using Django
I build web application with Angular 6 frontend, Django 1.11 backend and Hadoop 3.1. It seems to me that the problem is associated with uploading large files. My method in Django looks line shown below. Everything seems to be working fine with small files in different formats. However very often when I try to upload larger files I get the error shown at the bottom. Does anyone have an idea what can be wrong and how can I fix it? def post(self, request): key = request.META.get('HTTP_AUTHORIZATION').split()[1] user_id = Token.objects.get(key=key).user_id user_name = User.objects.get(id=user_id).username upload_file(request.FILES['file'], user_name) return Response(status=status.HTTP_201_CREATED) def upload_file(file, user_name): response = requests.put(url + ':9870/webhdfs/v1/user/' + str(user_name) + '/' + str(file) + '?op=CREATE&user.name=myuser&createflag=&createparent=true&overwrite=false' , data=file, headers={'content-type':'application/octet-stream'}) return response ERROR: django_1 | Internal Server Error: /cloud/ django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 600, in urlopen django_1 | chunked=chunked) django_1 | File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 354, in _make_request django_1 | conn.request(method, url, **httplib_request_kw) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1239, in request django_1 | self._send_request(method, url, body, headers, encode_chunked) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1285, in _send_request django_1 | self.endheaders(body, encode_chunked=encode_chunked) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1234, in endheaders django_1 | self._send_output(message_body, encode_chunked=encode_chunked) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1065, … -
Retrieve value from sum function
sum_acquired_value = Investment.objects.filter(customer=pk).aggregate(Sum('acquired_value')) The result is {'acquired_value__sum': Decimal('125000')} But I need the value '125000' to do calculations. -
Django Attribute error 'datetime.timedelta' object has no attribute 'decode'
I am using a simple generic view of django-rest-framework that is working fine on my local machine but gives an attribute error in the server. This is the error: AttributeError at /api/getcarts/ 'datetime.timedelta' object has no attribute 'decode' Here is the class: class GetCarts(generics.ListAPIView): serializer_class = CartSerializer queryset = TblCarts.objects.all() The strange thing is, all the other GET and POST APIs are working fine. Here is the TblCart: class TblCarts(models.Model): price = models.IntegerField() location = models.CharField(max_length=500) location_coordinate = models.CharField(max_length=100, default=0) number = models.CharField(max_length=50) promo_code = models.CharField(max_length=50, default=0) receipt = models.CharField(max_length=100) order_receive_date = models.DateField(auto_now_add=True) order_receive_time = models.TimeField(auto_now_add=True) order_dispatch_time = models.TimeField(default='00:00', max_length=100) order_delivered_time = models.TimeField(default='00:00', max_length=100) order_status = models.CharField(max_length=100, default=1) class Meta: managed = False db_table = 'tbl_carts' Here is the serializer: class CartSerializer(serializers.ModelSerializer): class Meta: model = TblCarts fields = '__all__' I cannot figure out what the problem is. The versions are: python 3.6.5, Django 2.1, djangorestframework 3.8.2. The error traceback: File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/views.py" in dispatch 483. response … -
Counting items in Django templates
Is it possible to tally items being listed as part of the django template within the html? For example, I have a django template with the following code snippet in it: <div> {% for thing in thing_list %} {% if thing.status == "n" %} <a>{{ thing.status.count }}</a> {% endif %} {% endfor %} </div> This django template displays all of the things in a list, and I can call each attribute of the thing and display it, so I know I have access to all of the fields. I want to count then number of "things" and display that number as text. My current attempt above isn't working. Does anyone have any suggestions? -
Expose python script to REST API using Django as the web framework
I have a couple of python scripts that make REST calls to a 3rd party tool. I have been tasked to include another 3rd party tool that acts as the gateway for customers to input information that is then being feed to the python scripts. I was asked to expose the python scripts (functions) as a REST API so that the parameters ( from the 3rd party tool) are passed within a REST API request (POST, PUT). Would Django be a good web framework to develop this functionality. Cheers, Roland -
file path of '/tmp' in Django Session
Right now i am using file based session in django to save data. SESSION_ENGINE = "django.contrib.sessions.backends.file" As per documentation django saves data in /tmp, but i dont understand what is actual path of this /tmp! Is this a directory in my project or else where? -
which programming lanuage is perfect for a project similar to opentable " table reservation system" and why?
If I want to make a system "Web app " similar to opentable or Yelp that specialized in table reservation, which programming language and frameworks is suitable for that problem, consider I have zero experience and I have just two months for coding? -
how to use pip3 to install django in windows 10?
I have created a virtual environment by using the command < py -m pip install virtualenvwrapper-win> . How I install django using pip3 ? -
React with Django adding fonts?
I have a React frontend running on a Django backend and I'm trying to import fonts( main open sans, open san sb) but main.js is different with Django, which is how most people suggest you import the fonts. Help! -
hosting company for Mezzanine project
what's the best web hosting for mezzanine plus shall I upload the virtualenv folder with the project or no I cant find a video about it -
What is the fastest way to order Django queryset using JSONField?
I have a model which mostly stores data in a JSON field. Its kinda set up as follows: class Record(models.Model): data = JSONField() Usually, the data field has the following format: data = { "name": "Chad", "age": 23 } Now, in a view, I want to get the first 20 records, but ordered using the format ['-age', 'name']. What are my options for doing this? Right now, the only solution I can think of is getting all the records using Record.objects.all(), and iterating the whole thing while ordering using the data field json. Is there a faster way to do this? Or is this my only solution? Moreover, if I am to solve it this way, how would I go about ordering the records, and would it be a huge performance issue on my database? Thanks. -
Django debug toolbar says I have a query that is duplicate 1367 times
I have a short view but with a complex query (the model that uses comes from a database mysql view). The problem is that when this view executes, template loads tooooo slow. The django debug tool shows that a query is duplicated 1367 times but the duplicated query has nothing to do with the complex database view query. 1)Is there any way to avoid duplicate query? 2)Is this delay because of the second query? Below, is my template and view code. Sorry for not showing them too good, but it is my first post in stackoverflow. simbouloi_list(request, eklid): paramorder = request.GET.get('orderoption', '') try: paramorder = int(paramorder) except: paramorder = 6 # default ταξινόμηση selected_ekloges = Eklogestbl.objects.filter(eklid=eklid) # επιλογή όλων των εκλ. αναμετρήσεων με visible=1 και κάνω φθίνουσα ταξινόμηση αν δεν δοθεί παράμετρος all_ekloges = Eklogestbl.objects.filter(visible=1).order_by('-eklid') #all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by('surname', 'firstname', 'fathername') if paramorder==1 or paramorder==6: all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by('surname', 'firstname','fathername') elif paramorder == 2: all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by('sindiasmos', 'surname', 'firstname','fathername') elif paramorder == 3: all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by('sindiasmos', 'toposeklogis', 'surname', 'firstname','fathername') elif paramorder == 4: all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by( 'toposeklogis','sindiasmos','surname', 'firstname','fathername') else: all_simbouloi = EklallsimbVw.objects.filter(eklid=eklid).order_by('toposeklogis', 'surname','firstname', 'fathername') context = {'all_ekloges': all_ekloges, 'selected_ekloges': selected_ekloges, 'all_simbouloi': all_simbouloi, } return render(request, 'Elections/simbouloi_list.html' , context) Template {% extends 'Elections/base.html' … -
Django rest framework Lists are not currently supported in HTML input
here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name class Catalog(models.Model): name = models.CharField(max_length=200) no_of_pcs = models.IntegerField(null=True,blank=True) per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2) company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog') def __str__(self): return self.name here is my seralizers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Avg,Max,Min,Count,F,Q HyperlinkedModelSerializer ModelSerializer class CatalogSerializer(serializers.HyperlinkedModelSerializer): dynamic_data = serializers.SerializerMethodField() class Meta: model = Catalog fields = '__all__' def get_dynamic_data(self, obj): totalpieces = Catalog.objects.all().aggregate(total_pieces=Count('no_of_pcs')) totalprice = Catalog.objects.all().aggregate(total_price=Sum('per_piece_price')) return totalprice,totalpieces class UserSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() company_name = serializers.StringRelatedField() class Meta: model = User fields = '__all__' class CatalogData(serializers.ModelSerializer): class Meta: model = Catalog fields = ('name', 'no_of_pcs', 'per_piece_price') class CompanySerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() catalog = CatalogData(many=True) user = UserSerializer(many=True) class Meta: model = Company fields = ('name', 'phone_number', 'catalog','user') here is my view.py from __future__ import unicode_literals from django.http import HttpResponse from .models import * import json from django.http import JsonResponse, HttpResponse from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets class CatalogView(viewsets.ModelViewSet): queryset = Catalog.objects.select_related('company_name') serializer_class = CatalogSerializer class CompanyView(viewsets.ModelViewSet): queryset = … -
How to access the instance from a model manager?
I was told that doesn't make since as managers operate on all rows not a single instance but I see what I want to achieve done in django-taggit library. Here: https://github.com/alex/django-taggit/blob/master/taggit/managers.py And the the installation works as follows: from django.db import models from taggit.managers import TaggableManager class Food(models.Model): # ... fields here tags = TaggableManager() Then to tag anything, one can simply do the following: apple.tags.add("red", "green", "fruit") Note: apple not Apple. Yet, when I try to do it myself, I get: AttributeError: Manager isn't accessible via MyModelName instances! -
File Browser no grapelli: NameError: name 'site' is not defined
I'm following this tutorial for install django-tinymce4-lite. At the end of the tutorial there are the indications to install django-filebrowser-no-grappelli. I use Django 2.1.1 but even though I've followed all the indications, after the installation of the file browser was shown this message: File "/var/www/html/dev/miosito/django/beautifulsite_v0.1.1/djangosite/djangosite/urls.py", line 25, in path('admin/filebrowser/', include(site.urls)), NameError: name 'site' is not defined Here is urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('testapp.urls')), #app for my tests path('tinymce/', include('tinymce.urls')), path('admin/filebrowser/', include(site.urls)), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) What I've wrong? -
How can I use Paramiko on Django?
Im trying to create a Web portal where users can enter the hostname of the remote server to copy logs or can SSH into and execute commands using Paramiko. How do I use django to do this? -
Django Rest Framework can't register route
I have the following code: # urls.py from django.contrib import admin from django.urls import include, path from rest_framework import routers from api import views router = routers.DefaultRouter() router.register(r'mymodel', views.MyModelViewSet, 'mymodel') urlpatterns = [ # ... path('api/', include(router.urls)), ] And the following ViewSet: class MyModelViewSet(viewsets.ViewSet): permission_classes = (OnlyStaffCanPost,) queryset = MyModel.objects.all() serializer_class = MyModelSerializer When I'm trying to access http://localhost:8000/api/mymodel/ it gives me Not Found error. I printed out router.urls, the output is: [<URLPattern '^$' [name='api-root']>, <URLPattern '^\.(?P<format>[a-z0-9]+)/?$' [name='api-root']>] Why my viewset doesn't get registered? -
IntegrityError: Problem installing fixture
I upload my first Django-project into DigitalOcean. After command python manage.py loaddata initial_data.json, I have received this message: django.db.utils.IntegrityError: Problem installing fixture '/webapps/django_shop/shop/initial_data.json': Could not load contenttypes.ContentType(pk=3): duplicate key value violates unique constraint "django_content_type_app_label_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(auth, permission) already exists. How can I fix it?