Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the most efficient way to store/cache heavy, repetitive operations on the backend?
I am using Django as a web server, and I am encountering a situation where I need to fetch top products from my DB to the memory based on filters, tags, and categories. Then I apply pagination before sending a JSON response to the frontend. The endpoint to this operation is the main feature in my app, hence I'd expect hundreds of the same request each minute. Since I have 10s of thousands of items in my DB, it is causing a lot of load on my system's infrastructure and it's leading to many undesireable drawbacks like slow response time, cost, etc. So the question is, are there any methods to handle temporal caching and storing of common tasks like getting the same list of products periodically in Django? My initial thought is as follows: - implement a periodic function - store the result of the function in some semi-DB - when users request that endpoint/function, it returns (without re-calculation) the paginated response I want to implement the above mentioned system in django, is it doable and what libraries and tool I have to use? I use Python 3.8 and Django 3.0.5 -
Transferring data from uploaded filefield to db (django, sqlite)
I am trying to transfer the data of the filefield files I upload using django to database. All what I am able to do is to upload data and stored in local directory. However, I'd like to save the data into database. The format of the files are principally csv files. models.py class UploadForm(models.Model): file = models.FileField() class Meta: db_table = "db_table" forms.py class UploadForm(forms.ModelForm): class Meta: model = UploadForm fields = "__all__" functions.py def handle_uploaded_file(f): with open('vps_app/static/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) views.py def index(request): if request.method == 'POST': Uploaded = UploadForm(request.POST, request.FILES) if Uploaded.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponse("File uploaded successfuly") else: Uploaded = UploadForm() return render(request, "index.html", {'form': Uploaded}) Help would be enormously appreciated -
Error in Django migrations, no changes detected
I've correctly done the "initial setup" with python manage.py migrate command and now in my mongodb database I see these collections: __schema__ auth_group auth_group_permissions auth_permission auth_user auth_user_groups auth_user_user_permissions django_admin_log django_content_type django_migrations django_session with object inside them so I'm pretty sure that I did it correctly and if I do it now it says: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. I think this is all normal, then i created this models.py file models.py from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=200, null=True) surname = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) When I try to do python manage.py makemigrations I get this "No changes detected". Adding my app name doesn't solve the problem. I have a migrations folder with init.py (with the __) in it. I don't understand why it worked for the initial setup and now it doesn't. If i put some syntax error in the models.py file the messages I get after running the commands are the same, so maybe models.py is being searched in another folder? Really don't know, anyway hope i wrote everything necessary, … -
how can i deal with this django problem "AttributeError at /profile/ 'CustomerProfileForm' object has no attribute 'cleaned_date'"
class ProfileView(View): def get(self, request): form = CustomerProfileForm() return render(request, 'profile.html', {'form': form, 'active': 'btn-primary'}) def post(self, request): form = CustomerProfileForm(request.POST) if form.is_valid(): user = request.user.username name = form.cleaned_data['name'] locality = form.cleaned_data['locality'] city = form.cleaned_data['city'] state = form.cleaned_data['state'] zipcode = form.cleaned_data['zipcode'] reg = Customer(user=user, name=name, locality=locality, city=city, state=state, zipcode=zipcode) reg.save(request) messages.success( request, 'Congratulation! profile update successfully') return render(request, 'profile.html', {'form': form, 'active': 'btn-primary'}) -
DjangoRestAPI filter a list field
in my DjangoRestAPI project i have 2 serialisers like this: serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tags fields = ['tagkey', 'tagval'] def create(self, validated_data): return Tags.objects.create(**validated_data) def update(self, instance, validated_data): instance.tagkey = validated_data.get('tagkey', instance.tagkey) instance.tagval = validated_data.get('tagval', instance.tagval) instance.save() return instance class ModvarSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') var_group = VarGroupSerializer(read_only=True) tag_var = TagSerializer(read_only=True, many=True) class Meta: model = ModbusVariable fields = ['id', 'short_name', 'uom', 'var_group', 'unit', 'writeable', 'value_class', 'address', 'bit_count', 'min_type','max_type', 'byte_order','function_code_read', 'is_quarterly', 'tag_var', 'owner'] def create(self, validated_data): ... well now in my views.py i have to create a ModVar list with a filter also for tag_var value: views.py class ModvarsList(generics.ListCreateAPIView): queryset = ModbusVariable.objects.using(random.choice(replica_list)).all() serializer_class = ModvarSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] pagination_class = StandardResultsSetPagination # paginator = None filter_backends = [DjangoFilterBackend] filterset_fields = { 'unit__port_id__master_id': ['exact'], 'unit__port_id__master_id__short_name': ['exact'], 'is_quarterly': ['exact'], 'tag_var': ['exact'] } search_fields = ['unit__port_id__master_id', 'unit__port_id__master_id__short_name', 'is_quarterly'] ordering_fields = '__all__' so if i run my API caall without filter i get this results: but if i try to filter for example using tag_var="tagkey: site1" or just "site1" i ever get the error The value is not correct for tag_var filter How can i expose just "key" and "value" field of tag_val value for filtering based on that values my API … -
django PostgreSQL arrayfield store a 3 dimension array
this is the list a want to store in my database : [30, 9.45, [3.4499999999999993, 1.0500000000000007], [10.625, 12.875], [14.075, 11.825], [9.0, 15.0], [12.904858299595142, 15.637651821862349], [15.0, 18.0], [1 .0, 1.0], [6.0, 10.5], [10.5, 6.0], [0.0, 0.0], [[3, 6], [3, 6, 6]], [[6.0, 1.5] , [10.5, 6.0, 4.5]], [27.0, 94.5], [110.1141194331984, 106.83476720647775]] my models.py : D240_TOTAL = ArrayField( ArrayField( models.FloatField(max_length=10, blank=True), blank=True, null=True, ), blank=True, null=True, ) but am getting the error : Field 'D240_TOTAL' expected a number but got [3, 6]. because my field is 2-d array but i am giving him a 3d array so how do i fixe that -
Problem when uploading a web made in django to aws
I am followint this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-configure-for-eb When I do: eb deploy I obtain the following error: [2021-07-08T12:48:37.858Z] ERROR [4740] : Command execution failed: Activity failed. (ElasticBeanstalk::ActivityFatalError) caused by: DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6 Collecting APScheduler==3.7.0 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) /opt/python/run/venv/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning. However I have a python version 3.9.5 Thank you -
Django else statement in html template not working
Why my else statement not working in html template. It should be display text "You don't have any notification" if user didn't have any notification. I am using else statement in my html template for showing the text but why text isn't showing? here is my code: {% for notification in notifications %} {%if user.id == notification.blog.author.id %} {% if notification.notification_type == "Comment Approved" %} Your Blog Post {{notification.blog.title}} received new commnet {%else%} <h1>Don't have any notification</h1> {% endif %} {%endif%} {%endfor%} when user don't have any notification I am getting empty html page. If user have notification then it's displaying but I am not understanding why my else statement not working when user don't have any notifications. -
How to make inline form in admin requiring some of the params?
I have the following code in django admin: class MarkFormatInline(admin.TabularInline): model = MarkFormat form = MarkFormatForm fields = ('format', 'url_template', 'start', 'count', 'delay', 'xmltimeout', 'adtimeout', 'only_fire', 'server_timeout') extra = 1 and the following form: class MarkFormatForm(forms.ModelForm): class Meta: widgets = { 'xmltimeout': AdminIntegerFieldWidget(), 'adtimeout': AdminIntegerFieldWidget(), } I need to make the url_template field mandatory non-empty and the only_fire flag mandatory to False. How to implement it in Django? -
Can I save input and output data from dash applications in Django database?
I have created few plotly dash applications and integrated them into my Django web application. I wanted to know if we can save using input and output values in our Django database. Is also possible to load this data into the dash apps? -
Accessing one model from within another in Django many-to-one using ForeignKey
Lets imagine we have two models (many-to-one model). Code below shows that a reporter can have multiple articles class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField(null=True) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE, null=True) def __str__(self): return self.headline Let's see what I have in my database on this model. # Reporter.objects.all().values() # <QuerySet [ # {'id': 1, 'first_name': 'John', 'last_name': 'Smith', 'email': 'john@example.com'}, # {'id': 2, 'first_name': 'Paul', 'last_name': 'Jones', 'email': 'paul@example.com'} # ]> # Article.objects.all().values() # <QuerySet [ # {'id': 5, 'headline': "1st headline", 'pub_date': datetime.date(2005, 7, 29), # 'reporter_id': 1}, # {'id': 6, 'headline': "2nd headline", 'pub_date': datetime.date(2006, 1, 17), # 'reporter_id': 2}, # {'id': 7, 'headline': '3rd headline', 'pub_date': datetime.date(2005, 7, 27), # 'reporter_id': 1} # ]> The first reporter has two publications and second has the only. I need to get the list of all articles for each reporter. I tried this way (according to django docs): Article.objects.filter(reporter__first_name='John') It's okay. It works. I also tried to instantiate the first reporter as 'r1' and then do this: r1.article_set.all() And this piece of code works too. But as I'm new to django, … -
Heroku can't connect fonts
I have downloaded fonts for html template that is converted with xhtml2pdf to pdf. I didn't manage to google for answer that works for me. I thought that path was changed but in heroku bash path isn't changed. Here is my code: fonts are in invoices/static/invoices/fonts settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'main/static'), #os.path.join(BASE_DIR, 'invoices/static'), #BASE_DIR / "static", ] STATIC_ROOT os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage. CompressedManifestStaticFilesStorage' html font connect <html lang="ru"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html" > <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Инвойс #{{invoice_id}}</title> <style> @font-face { font-family: 'Roboto-Medium'; src: url(../invoices/static/invoices/fonts/Roboto-Medium.ttf); } </style> -
How to run Django migrations inside kubernetes and apply changes to the database pod?
I have deployed my app to Azure with Kubernetes. I have separate pods for front end, back end and database. I encountered problems when one of my database fields changed from id to userId. I have tried to update this change to my deployment database but without any luck. I logged into my back end pod and removed the existing migration file and run python manage.py makemigrations & python manage.py migrate. After these I checked that everything was ok in the migration file. After this I don't know what to do. Do I need to remove the database pod and create it again? Or how do I update the database inside the pod? -
Why are uploaded images via Django admin not showing up in the production server?
I have the following model field logo = models.ImageField(upload_to=municipality_logo_file_name) and function that uploads the image to the desired location. def municipality_logo_file_name(instance, filename): name, extension = os.path.splitext(filename) return os.path.join('municipality', 'logo', str(uuid.uuid4()) + extension.lower()) In the development mode, a file uploads correctly to for example /media/municipality/logo/1e3cc24a-841b-4577-aa59-b53e5b10420b.png and then displays correctly in the template using <img src="{{ municipality.logo.url }}" alt="Logo obce" style="max-height: 8rem; width: auto"> In the production, file uploads well, but does not display in the template and the url cannot be followed to display image, the response is Not Found The requested resource was not found on this server. Any hint as to why this might be happening would be much appreciated. -
DJANGO translate complex template variable
I would like to translate a more 'complex' template variable, however I am running into unexpected error. The simple texts on my template are translated properly. I have a template variable that looks like this: {{ days|index:class.gym_class.day }} days is a list of week days, index is a custom tag that looks looks like this: @register.filter def index(List, i): return List[int(i)] The variable evaluates to "Monday" I have this in my .po file, and the .po file is compiled msgid "Monday" msgstr "Hétfő" Now if I want to translate the variable like this: <td>{% trans days|index:class.gym_class.day %}</td> I get an error: AttributeError at /hu/login 'list' object has no attribute 'replace' To me it seems, that the translation tries to happen before the template tag evaluation? I also tried <td>{% blocktrans %}{{ days|index:class.gym_class.day }}{% endblocktrans %}</td> Which interestingly returned nothing. Neither "Monday" neither "Hétfő" is printed. How can this problem be solved? -
DJANGO translate template variable
I am having problems translating template variables according to this thread: django translate variable content in template Simple text on the template get translated perfectly, however evaluated template variables dont. I have a template that looks like this: <td>{{ days|index:class.booking.day }}</td> The variable there evaluates to "Monday", with capital M and no spaces. In my .po file, I have msgid "Monday" msgstr "Hétfő" After compiling the .po file I thought I should be able to translate this by <td>{% trans days|index:class.booking.day %}</td> But only "Monday" is shown, not its translation. I also tried blocktrans to no avail <td>{% blocktrans %}{{ days|index:class.booking.day }}{% endblocktrans %}</td> What am I doing wrong? -
'QuerySet' object has no attribute 'save' Error Occurred
I am a student studying Django. Currently, the member information has been entered in the Member table. I want to create Mypage so that member information registered in the Member table can be modified, and develop so that member information can be modified on Mypage. But while developing, I faced the following error: How can I solve this? Any help would be greatly appreciated. Detail Error : AttributeError at /mypage/mypage_modify/ 'QuerySet' object has no attribute 'save' Request Method: POST Request URL: http://127.0.0.1:8000/mypage/mypage_modify/ Django Version: 3.1.5 Exception Type: AttributeError Exception Value: 'QuerySet' object has no attribute 'save' Exception Location: C:\zeronine_project\mypage\views.py, line 27, in mypage_modify Python Executable: D:\anaconda3\envs\vnv_zn\python.exe Python Version: 3.7.6 Python Path: ['C:\\zeronine_project', 'D:\\anaconda3\\envs\\vnv_zn\\python37.zip', 'D:\\anaconda3\\envs\\vnv_zn\\DLLs', 'D:\\anaconda3\\envs\\vnv_zn\\lib', 'D:\\anaconda3\\envs\\vnv_zn', 'D:\\anaconda3\\envs\\vnv_zn\\lib\\site-packages'] Server time: Thu, 08 Jul 2021 21:05:53 +0900 view.py from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from mypage.forms import * from zeronine.models import * # Create your views here. def mypage_list(request): categories = Category.objects.all() return render(request, 'mypage/mypage_list.html', {'categories':categories}) def mypage_modify(request): current_category = None categories = Category.objects.all() member = Member.objects.all() if not request.user.is_authenticated: return HttpResponseRedirect(reverse('zeronine:login')) if request.method == "POST": member.name = request.POST['name'] member.password = request.POST['password'] member.username = request.user member.save() return redirect('zeronine:post') else: memberForm = MemberForm return render(request, 'mypage/mypage_modify.html', {'memberForm':memberForm, 'member':member, 'current_category': current_category, … -
How to get choices field from django models in a list?
I have a model having choices field. I want to fetch the choices options in a list.please help me to achieve that OPTIONS = ( ('COOL', 'COOL'), ('WARM', 'WARM'), ) class My_Model(models.Model): options = models.CharField(max_length=20, choices=OPTIONS, default=None,blank=True, null=True) I want options values in a list like ['COOL','WARM'], How to achieve it, I tried something like My_Model.options but it is not working -
Angular CRUD backend frontend
In Django I build a backend, with the Model Person, which contains of two foreign keys: 'gender' and 'work'. I have build the REST API for the app and it is working as intended. When I try to create a Person in my Angular frontend, I get the multiple select options for 'work', but no for 'gender' - which is weird, because I just applied the same code for the both of them. This is my Form Field in Angular to create Person: When I try to select form Gender Foreign Key, I get nothing, but for Work Foreign Key it works perfect. I will do edits with code, if you tell me which files are needed. Because I have no idea where my error is. -
How to convert integer months to year in python
I have inputs start date and end date. I want output like 2 years 7 months from dateutil.relativedelta import relativedelta rdelta = relativedelta(now, birthdate) print 'years - ', rdelta.years print 'months - ', rdelta.months in this method, I got output like >>> years - 2 >>> months - 18 I prefer output like I want output like 2 years 7 months -
Blog Category Slugify is not working in Django
I am getting an error when I click on the post category it says Field 'id' expected a number but got 'coding'. Each post is added under a category below is my Code: Model: class Item(models.Model): title = models.CharField(max_length=100) description= RichTextField(blank=True, null=True) main_image= models.ImageField(null=True, blank=True,upload_to='images/') date = models.DateTimeField(auto_now_add=True) item_category = models.ForeignKey(Categories, default='Coding', on_delete=SET_DEFAULT) slug = models.SlugField(null=False, unique=True) # new View: def CategoryView(request, cats): category_posts = Item.objects.filter(item_category=cats.replace('-','')) return render(request, 'waqart/categories.html', {'cats':cats.title(), 'category_posts':category_posts }) URL: urlpatterns = [ path('', ItemListView.as_view(), name='waqart-home'), path('add_item/', ItemCreateView.as_view(), name='create_item'), path('item/<int:pk>/', ItemDetailView.as_view(), name='item_detail'), path('item/edit/<int:pk>/', ItemUpdateView.as_view(), name='item_update'), path('category/<str:cats>/', CategoryView, name='category'), I am new to django appreciate if anyone can solve this for me -
How to get a full path of file uploaded via HTML form in django view.py file?
home.html <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name = 'img' > <button type="submit"> Post On Facebook </button> </form> views.py def home(request): if request.method == 'POST': # get the image absolute location return render(request,'home.html') I want the file path, so that I can upload the file on facebook using GraphAPI. -
Where to store raw SQLs on Django Project
In my Django project I'm using two dbs. Postgres which works with ORM and Bigquery. To query Bigquery I have a bunch of extensives SQLs and I dont want to store it on a View. Curently I'm storing in a folder called queries in the same level of views folder. But I keep asking myself if those SQLs should be in models folder in some way. Well, where is the best place to store raw SQLs on a Django Project? -
Django admin do not display all fields
This question is created to help other people with similar problem. I know how to fix the issue, but I'm also interested Why this happens. In my models.py I've had a model class CEOSetting(models.Model): title = models.CharField('Заголовок', help_text='Содержимое тега <title>. Так-же поддерживает переменные.', max_length=200, blank=True) page = models.CharField('Описание страницы', max_length=120) key = models.CharField('Ключ', max_length=50, unique=True) variables = models.TextField('Доступные переменные', null=True, blank=True) description = models.TextField('Meta description', blank=True) keywords = models.TextField('Meta keywords', blank=True) robots = models.TextField('Meta robots', blank=True) And registered this model in admin.py @admin.register(CEOSetting) class CEOSettingAdmin(admin.ModelAdmin): pass When I've tried to add or edit CEOSetting record in admin, the admin site was showing me only one field (title) and nothing more. Even buttons at bottom of the page were missing. -
Save position in sortable list
I'm trying to make an sortable list for a website with Django, I need to keep the order of the cards when they are changed position, saving this in a database table. The POST method below, returns me the old position of the card, the new position and the ID of a card. $(function() { var start_pos; var end_pos; var id; $('#sortable').sortable({ start: function(event, ui) { start_pos = ui.item.index(); ui.item.data('start_pos', start_pos); }, stop: function(event, ui) { end_pos = ui.item.index(); id = ui.item.attr("id"); $.ajax({ url: "/project/", data:{ start_pos, end_pos, id, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken').val() }, method: 'POST', }) }, update: function(event, ui) { $('#sortable li').removeClass('highlights'); } }); }); In the database, each card have a ID and and "order_number" fields, when the card changes, I want to keep the ID the same and the "order_number" change, replacing the older "order_number". I don't have any idea how make an SQL statement to save this order or something in the jQuery code. Thanks in advance!