Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retrieve user selections from a previous form
I have several forms that take people through steps and below are the first two and the simplest ones and makes it easy to explain what i am having problem with. The following two views are login required and contain one form on each. First view is the new_operator where the user fills out a single text input field. Second view is the new_asset where the user fills one text input field as the asset name and selects an operator from the a select/dropdown field. The question is how can i get the form to remember the operator name the user created in the previous form and make it as the default option? To be clear, i still want the user to select any other operator if they choose to do so but i want the option they just created to be the default. Thanks a lot in advance for the help. First, here are the models: class OperatorCompany(models.Model): name = models.CharField(max_length=50, unique=True) created_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(User, related_name='operator_added_by', null=True, on_delete=models.SET_NULL) class Meta: verbose_name = "Operator Company" verbose_name_plural = "Operator Companies" def __str__(self): return self.name class AssetName(models.Model): name = models.CharField(max_length=50, unique=True) operator = models.ForeignKey(OperatorCompany, related_name='asset', on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) … -
Dockerized Django tests only look at first $PATH location
I'm running a Django test suite in a Docker container, and some of these tests use a program I've had to apt-get install (wkhtmltopdf). Now I can see that it's been installed correctly: $ wkhtmltopdf --version wkhtmltopdf 0.12.5 but for some reason the Django test can't use it. The installation location is definitely on my $PATH (third to last element): $ echo $PATH /usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin $ find / -name wkhtmltopdf /usr/bin/wkhtmltopdf However when I run tests I get a stack trace ending in: OSError: No wkhtmltopdf executable found: "/usr/local/bin/wkhtmltopdf" If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf Now it's absolutely correct that there is no /usr/local/bin/wkhtmltopdf, because it got installed elsewhere (/usr/bin/) but both those locations are on $PATH. I've tried moving /usr/bin/ to the start of $PATH, but I then get the error: Traceback (most recent call last): File "./manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management presumably because it's now looking in /usr/bin/ for django when it's actually in usr/local/bin/, which is no longer the first location on $PATH. I'm not sure if the problem is a Docker one, a Django one, a … -
Django, autocomplete-light, empty drop down menu instead of auto search
Autocomplete, supposedly, has to be able to bring choices under the entry field, when a person starts typing into the field... I followed this tutorial: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#overview I tried all other recommendations, like: django-autocomplete-light displays empty dropdown in the form or django-autocompletion-light simple foreign key completion shows not editable drop-down widget And many other advices, but nothing worked for me somehow. Also I tried to tiе foreign key and use without foreign key in the model which comes from postgresql database. Nothing helped so far, sometimes followed advises brought extra errors. The search entry field, is blocked. Instead, there is drop down field, in which there is no choices. Thank you for your help! Here is my code so far: Models.py(lost tabs and spaces when copied code, but in the code it is as it should be): from django.db import models from django import forms from django.urls import reverse from django.forms import ModelForm class ForQuery(models.Model): query_id = models.BigAutoField(primary_key=True) dep_st = models.CharField(max_length=35, blank=True, null=True)//tried to make it as foreign //key from DeptDic, brings drop down menu with half of raws from the column code_dep_st = models.CharField(max_length=5, blank=True, null=True) dep_kind = models.ForeignKey(Classification, models.DO_NOTHING, db_column='met_kind', blank=True, null=True) class Meta: managed = False db_table = … -
User profile form_is_valid() doesn't save
I implemented Profile create using post save signals Models: class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): """User additional information""" email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) users = ( ('doctor', 'Doctor'), ('patient', 'Patient'), ('assistant', 'Assistant'), ) user_type = models.CharField(choices=users, max_length=9, default='patient') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Profile(models.Model): name = models.CharField(max_length=20, verbose_name='Имя', blank=True, null=True) surname = models.CharField(max_length=20, verbose_name='Фамилия', blank=True, null=True) third_name = models.CharField(max_length=20, verbose_name='Отчество', blank=True, null=True) birth_date = models.DateField(blank=True, null=True) address = models.CharField(max_length=200, verbose_name='Адрес', blank=True, null=True) mobile_phone = models.IntegerField(verbose_name='Номер телефона', blank=True, null=True) avatar = models.ImageField(upload_to='images/avatars/%Y/%m/%d/', default='/static/default_img/default.png') class Meta: abstract = True class Patient(Profile): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) diagnose … -
How to show admin specific information on my Django website?
I'm currently building a Hospital Management system with Django but encountered an issue. In this website, admins will register for their respective hospitals and manage their doctors, patients etc. But, I don't want one hospital's admin to see the informations of ther hospitals' doctors or patients. So how can I make sure that the admin only sees the data of his own hospital and not others'. What changes can I make in my models to do so? -
Link the Copyright attribute and image file with BeautifulSoup
I need to download and link the Copyright attribute and image file name. The problem is that img, together with src, is inside the tag, which has a 'Copyright' key in the date. Using BeautifulSoup I managed to download 'Copyright' but how to link it with img? code with html <wphimage data="{'FileId':6182,'Copyright':'John Smith','Alignment':'left','ZoomDisabled':false,'ImageOnly':false,'AlternativeText':'John Smith','ImageVersion':'conductorportraitlong','tabid':0,'moduleid':0}"> <span style="display:block; float:left;" class="DIV_imageWrapper"> <a data-lightview-title="Adela Frasineanu" data-lightview-caption="" class="lightview" href="//example.com/static/images/image.JPG"> <img src="//example.com/static/images/image.JPG" alt="John Smith"> </a> <a href="javascript:;">≡ <span>John Smith</span></a> <a class="A_zoom lightview" href="//example.com/static/images/image.JPG" data-lightview-title="John Smith" data-lightview-caption="">+ </a> </span> </wphimage> code in py below soup = BeautifulSoup(row['Text'], features="html5lib") wphimages = soup.findAll('wphimage') for index, img in enumerate(wphimages): dict_as_str = img["data"].replace("'", '"') copyright_text.append((row["id"], json.loads(dict_as_str)['Copyright'])) -
Django migrations and transactions in MySQL
Had an issue where one of the django (data) migrations was marked as executed, to create a record in the database, but couldn't find the actual record. That ran just fine in stage, creating the record, but in production it was only marked as executed. A migration that was executed after it failed/crashed, which could explain part of the issue. Here is the list of most recent migrations, with date/time when they were executed: network_list 0002 was supposed to create the record, and solution 0039 was the one that crashed, immediately after 0038 execution. 0039 was only executed on a next deploy. Ended up with a few questions on my head: When django migrations are executed, ALL of them run inside a transaction as I thought, OR only each individual migration run inside it's own transaction? From django docs (links below), I saw MySQL have a crappy support for transaction during migrations. Could that issue have been caused by MySQL? Any other ideas on what could have caused this to be marked as executed, but the record is missing? https://docs.djangoproject.com/en/3.0/howto/writing-migrations/#non-atomic-migrations https://docs.djangoproject.com/en/3.0/topics/migrations/#mysql Using Django 1.8 and MySQL/Aurora. -
Why does the Model Form fail to render in django
I'm trying to display a select box within a table in Django. Unfortunately, when I put the form within the HTML template it does not render although other elements do. forms.py: resultchoices = [ ('Not Started', 'Not Started'), ('Pass', 'Pass'), ('Issues', 'Issues'), ('N/A', 'N/A'), ] class checklistform(ModelForm): class Meta: model = checklist fields = "__all__" widgets = { 'INFO_001_result': Select(choices=resultchoices,), } models.py: class checklist(models.Model): resultchoices = [ ('Not Started','Not Started'), ('Pass', 'Pass'), ('Issues', 'Issues'), ('N/A', 'N/A'), ] INFO_001_result = models.CharField(choices=resultchoices,default='Not Started',null=False,max_length=11), INFO_001_remark = models.CharField(null=True,default='',max_length=400) Views.py: checklistform = checklistform # Create your views here. def checklist(request): context = { 'checklistform': checklistform, } return render(request, 'pages/Checklist.html',context ) HTML template: <td style="text-align:Center;background-color:#44546A;color:#000000;font-size:10px;width:108px;border: 1px solid #999999; " eth-cell="E5" >{{ checklistform.INFO_001_result }}</td> <td style="color:#000000;font-size:10px;width:88px;border: 1px solid #999999; " eth-cell="F5" >{{ checklistform.INFO_001_remark }}</td> </tr> Django doesn't give me any error it just fails to render that section within the template. -
Can not use opencv to read a video in Apache+WSGI+Django but ok in just Django
I use Django and Apache. When I run this: video_capture = cv2.VideoCapture(path) fps = video_capture.get(cv2.CAP_PROP_FPS) height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT)) success, frame = video_capture.read() It will run success, frame = video_capture.read() forever and not return. But fps height width frame_count is correct. If I just use Django by python manage.py runserver 0.0.0.0:8000, the code is correct. So I think I make a mistake in using WSGI. Here is how I use WSGI+Apache+Django. I manage Python with Anaconda. If I install mod_wsgi directly it will report an error, so I download mod-wsgi in https://pypi.org/project/mod-wsgi/#files. Then tar it and run ./configure --with-apxs=/usr/bin/apxs --with-python=/home/lhl/anaconda3/envs/web/bin/python make && make install. I use whereis to find the path. Then I use pip install mod_wsgi to install mod_wsgi in anaconda env web. Finally I run mod_wsgi-express module-config and copy the output LoadModule wsgi_module "/home/lhl/anaconda3/envs/web/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so" WSGIPythonHome "/home/lhl/anaconda3/envs/web" to http.conf of Apache. Is there an error? Think you very much! -
Django REST Framework change rederer class based on response
I'm using Django 2.2 and Django REST Framework. I have an APIView which will download Zip file on success response. class MultiDownloadCode(APIView): serializer_class = MultiDownloadSerializer permission_classes = ( IsAuthenticated, CodeCanExport, ) renderer_classes = (ZipRenderer,) def post(self, request): ... mime_type = 'application/zip' file_name = '{}.zip'.format(random_string(20)) response = Response(data=in_memory_zip.read(), content_type=mime_type) response['Content-Disposition'] = 'attachment; filename=%s' % "-".join(file_name.split()) return response I have created a custom Renderer class ZipRenderer class ZipRenderer(BaseRenderer): media_type = 'application/zip' format = 'zip' charset = 'utf-8' render_style = 'binary' def render(self, data, accepted_media_type=None, renderer_context=None): return data This is working fine in case of a successful response. But in case of permission denied exception, the error messages are also binary encoded and not proper JSON rendered. When I add JSONRenderer to the renderer_classes renderer_classes = (ZipRenderer, JSONRenderer) This works fine in case of exception but then gives error in case of a success response. How can I change the renderer based on the response? -
django saving database records and using only those records, not previously saved records
I am learning django. I want to save 3 or 4 records in database and use only those records in detailed view but not previously stored records. I don't know how to implement. -
Sweetalert closes suddenly after appearing because of page reload
I'm using javascript sweetalert in Django html template. Sweetalert dialog closes after appearing because of page reload. I have applied the suggested fixes in answer to the Question-javascript-sweetalert-popup-closes-itself-after-a-quick-second My template code is <button title="Transform" id="transform_btn" type="button" class="btn" style="color:white;background-color:#fff;"> <a href="/load_to_hive/{{stu.cases_id}}/"> <i class="glyphicon glyphicon-hourglass fa-2x"></i> </a> </button> And javascript code displaying the dialog is {% block javascript %} <script src="{% static 'js/sweetalert.min.js' %}"></script> <script> var transformBtn= document.getElementById('transform_btn'); transformBtn.addEventListener("click",function(){ swal({ title: "Good job!", text: "You clicked the button!", icon: "success", }); }) </script> {% endblock javascript %} -
Django-Registration through axios Post
I try to register an User using django-registration.one_step.views but I cannot seem to succes and I could not debug what is the missing part. I have urls in my Django side path('accounts/register/', RegistrationView.as_view( form_class=YogaUserForm, success_url="/" ), name="django_registration_register"), path('accounts/', include('django_registration.backends.one_step.urls')), path('accounts/', include('django.contrib.auth.urls')) In vuejs application I have used vuex and axios async registerUser(context, payload) { try { const response = await DjangoAPI.register(payload); return Promise.resolve(response); } catch(err) { console.log('err in store.user/registerUser', err); return Promise.reject(err); } }, async register(payload) { try { const {username, password1, password2, email} = {...payload}; const response = await apiCall .post('/accounts/register/', { email, password1, password2, username }); console.log("test"); console.log(response); return Promise.resolve(response); } catch(err) { console.log('err in DjangoService/register', err); return Promise.reject(err); } }, When I try to register, nothing happens, I get console.logs(): config: adapter: ƒ xhrAdapter(config) baseURL: "http://localhost:8000/" data: "{"email":"random@random.com","password1":"ne12veryt..","password2":"ne12veryt..","username":"random"}" headers: {Accept: "application/json, text/plain, */*", Content-Type: "application/json;charset=utf-8", Authorization: "Bearer null", X-CSRFTOKEN: "hqyVxsYXxI929ZtB5arssIDt3yq5O6acEJGdkmAdPYQhhN4RXPq2jl18Vj65Z2cm"} method: "post" url: "/accounts/register/" xsrfCookieName: "csrftoken" xsrfHeaderName: "X-CSRFTOKEN" headers: {access-control-allow-credentials: "true", access-control-allow-origin: "http://localhost:8000", content-language: "tr", content-length: "8361", content-type: "text/html; charset=utf-8", …} request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …} status: 200 statusText: "OK" How can I fix my registration when using django-registration? Best Regards -
Django admin. Add 'select group' to custom user model ForeignKey
Goodmorning everyone. First post so apologies if something wrong. I'm trying to add the possibility to add a custom user to a group from the django admin panel. I can do it while registering an Account user but not registering an Affiliateuser which is linked to the Accountuser by : models.ForeignKey(Account, null=True, on_delete=models.SET_NULL, limit_choices_to={'groups__name': 'Super'}) In my models.py i create an AccountManager class extending BaseUserManager. I also create the Account class (extending AbstractBaseUser and PermissionsMixindefining the USERNAME_FIELD and REQUIRED_FIELDS) and the Affiliateclass (extending models.Model and with ForeignKey stated above). Registering an Affiliate from the webpage it directly goes to the 'Affiliate' group, but when doing it from the admin I can't choose. I think I have to modify something in admin.py, but I'm not sure. Here's my admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserChangeForm, UserCreationForm from .models import * class AccountAdmin(UserAdmin): list_display = ('username', 'email', 'first_name', 'last_name', 'date_joined', 'last_login', 'is_admin', 'is_superuser') search_fields = ('email', 'username', 'ref_code') readonly_fields = ('date_joined', 'last_login') filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Account, AccountAdmin) admin.site.register(Affiliate) models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password=None): if not … -
Test the instance attribute in signal function django before to execute
I Try to put if statement in my post_save signal to check the instance attribute and execute the good instruction. I have 3 profiles User (3 table wich are link witch my costume User mode by OneToOneField. I have the flags is_student, is_teacher and is_manager (BooleanFielsd) in my User model. So I want to check the flag wich is True and execute the save. from django.db.models.signals import post_save from accounts.models import User, Student, Teacher, Manager from django.dispatch import receiver @receiver(post_save, sender=User) def sign_up_student_profile(sender, instance, created, **kwargs): if (instance.is_student ==True): Student.objects.create(user=instance) elif (instance.is_teacher ==True): Teacher.objects.create(user=instance) elif (instance.is_manager ==True): Manager.objects.create(user=instance) else: pass -
Could somebody please help me for this requirement?
This is what I want to achieve. The url needs to be called through ajax as well. The requirement is to calculate similar things in back end and from front end using ajax call. I have to pass some dictionary/json object in the url and get the result. class SomeName(View): def get(self, request, *args, **kwargs): # GET method . . # Calling nother url: '/url-to-calculate-something/' # Needs to pass dict object in the above url # Get response and use this like below context = {'value': 'calculated_value'} . . response = TemplateResponse(request, 'template_name', context) return response urlpattern = [ re_path(r'/url-to-calculate-something/', CalculationDef, name='some-calculation') ] def CalculationDef(View): # Here another call to some api # Get result return result -
how to get sessionid from Cookie in browser using jquery?
I am using js.cookie CDN to get cookie .In my browser there is a Cookie with name sessionid ,(set by django backend itself) ,having some value , but Cookie.get('sessionid') is giving undefined //CDN : <script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script> -
Dynamically load content in Bootstrap Modal with AJAX with Django
I am a begineer in Django framework I want to Dynamically load content in Bootstrap Modal with AJAX something like this https://makitweb.com/demo/modal_ajax/index.php I found many tutorials on internet but i want some guidance on the part where button is pressed and modal shows data related to that item. Please pardon me if it's a bad question. -
Two views with only one diffrent line of code
I have two views with only one diffrent line of code, rest is same in both views. How to prevent repetition of code? Can i delete tag_view and add optional parameter as kwarg to index and depending on it return view without specific tag or with tag? Is it how it should work? My views below. def index(request): post_form = AddPostForm(request.POST or None, instance=request.user) comment_form = AddCommentForm(request.POST or None, instance=request.user) if request.method == 'POST': # FORMULARZ DODAWANIA POSTU if post_form.is_valid(): post_form.save() create_notifications(post_form.instance) # FORMULARZ DODAWANIA KOMENTARZA if comment_form.is_valid(): comment_form.save() (posts, comments) = serve_post_and_comments_except_blocked(request) return render(request, 'mikroblog/index.html', {'posts': posts, 'comments': comments, 'post_form': post_form, 'comment_form': comment_form}) def tag_view(request, tag): post_form = AddPostForm(request.POST or None, instance=request.user) comment_form = AddCommentForm(request.POST or None, instance=request.user) if request.method == 'POST': # FORMULARZ DODAWANIA POSTU if post_form.is_valid(): post_form.save() create_notifications(post_form.instance) # FORMULARZ DODAWANIA KOMENTARZA if comment_form.is_valid(): comment_form.save() (posts, comments) = serve_post_and_comments_except_blocked(request) posts.filter(content_post__contains=tag) actual_tag = tag return render(request, 'mikroblog/tag.html', {'posts': posts, 'actual_tag': actual_tag, 'comments': comments, 'post_form': post_form, 'comment_form': comment_form}) -
Postgres raw query for foreign key in Django
I had written a SQL raw query in python for the Postgres database. However, the following query I wrote for was when my Song field in my Django model was a many-to-many field. But, due to other requirements, the same Song field in the model has been changed to the foreign key. The issue, I am facing is that the query doesn't runs successfully and returns an error. I had written two raw Postgres queries: First query:(Using left join) select songs.id, songs.name, songs.artist, songs.album, songs.albumart, songs."albumartThumbnail", cpr.votes, is_requested from ( select id, name, artist, album, albumart, "albumartThumbnail" from ( select song_id from core_plsongassociation where playlist_id in (1477) ) as sinpl left join songs on sinpl.song_id=id where explicit=False ) as songs left join ( select song_id, votes, bool_or(thirdpartyuser_id=177) as is_requested from ( select * from core_priorityrequests where client_id=2876 and is_played=False ) as clpr left join core_priorityrequests_third_party_user on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes ) as cpr on songs.id=cpr.song_id left join ( select core_blockedsongs_song.song_id from core_blockedsongs join core_blockedsongs_song on core_blockedsongs.id=core_blockedsongs_song.blockedsongs_id where core_blockedsongs.unblock_flag = 'f' and core_blockedsongs.client_id=2870 ) as c on c.song_id = songs.id where c.song_id is null; Second Query(without using left join): select songs.id, songs.name, songs.artist, songs.album, songs.albumart, songs."albumartThumbnail", cpr.votes, is_requested from … -
Why I cannot save the new form to database?
I really don't know what's the problem of my code.I'm using django connected to my database, and try to save my new data into database, here is the models.py: class guest_room(models.Model): room_number=models.CharField(max_length=25,primary_key=True) room_type=models.CharField(max_length=25) room_status=models.CharField(max_length=25) Here is the form.py: class guest_room_form(forms.ModelForm): class Meta: model = guest_room fields = ['room_number', 'room_type', 'room_status'] widgets = { 'room_number': forms.TextInput(attrs={ 'class': 'form-control' }), 'room_type': forms.TextInput(attrs={ 'class': 'form-control' }), 'room_status': forms.TextInput(attrs={ 'class': 'form-control' }), } Here is the views.py: def addnewroom(request): if request.method=="post": form=guest_room_form(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect("guestroom") else: form=guest_room_form() return render(request,'addnewroom.html',{'form':form}) This is my html of the add new data page: <form method="POST" class="post-form" action="../addnewroom/"> {% csrf_token %} <div class="container"> <br> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <h3>Enter Details</h3> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Room Number:</label> <div class="col-sm-4"> {{ form.room_number }} </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee Email:</label> <div class="col-sm-4"> {{ form.room_type }} </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee Contact:</label> <div class="col-sm-4"> {{ form.room_status }} </div> </div> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </div> </form> I want to go back to the 'guestroom.html' after submitting successfully, but now after I submit, it stayed at the same page. I … -
How to display all the children of parent category?
Here I want to display all the child categories of a parent category if it has child. But the below code in my templates not working properly. How to properly get all the child categories of a particular parent in the templates here ? model class Category(models.Model): parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) nesting_level = models.IntegerField(default=0) title = models.CharField(max_length=255, unique=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views class ListCategoryView(generic.ListView): model = Category context_object_name = 'categories' template_name = 'list_categories.html' ordering = '-created' template <td class="text-primary"> {{category.title}} </td> <td class="text-primary toggle">{% if category.parent %}{{category.parent.title}} {{category.category_set.all.count}} # not working properly {% else %} None {% endif %} <div class="table-dialog"> {% for category in category.category_set.all %} {{category}}{% if not forloop.last %}, {% endif %} #not working properly {% endfor %} </div> </td> <td>{{category.created}}</td> -
Reduce the execution time of django view
I have a django view which returns all the products of Product model. Situation is discount is dependent on product as well as user so it has to be calculated every time at runtime. I have added only 3500 products yet and server is taking 40-50 seconds to respond. I wonder how much time will it take when i will add 100,000 products. How can i optimize this? @login_required def product_list(request): context = {} product_qs = Product.objects.all() product_list = [] for product in product_qs: discount_applied_product = apply_discount(product,request.user) product_list.append(discount_applied_product) context['products'] = product_list return render(request,"myapp/products.html",context) I have deployed website on Google App engine standard. If i increase gunicorn workers, is it going to help? -
Django ORM Prefetch and filter results
I want to filter GeneralItem by manytomany items without null (filtered by Prefetch): class GeneralItem(models.Model): title = models.CharField(max_length=250) items = models.ManyToManyField('MediaItem') qs = GeneralItem.objects.prefetch_related( Prefetch( 'items', queryset=MediaItem.objects.filter(**item_params), to_attr='custom_items' ) ).filter(custom_items__isnull=False) But I get error: Cannot resolve keyword 'custom_items' into field. Choices are: items, title Is there a way to filter this? -
Conditional unique_together in Django
I have following unique constraint in my model. class Meta: unique_together = (('crop', 'order', 'sku'),) But sku may be null in some cases and in that case this unique_together is not working as null is not equal to null.i am thinking to make a conditional unique_together like if sku is not null then (('crop', 'order', 'sku'),) else (('crop', 'order'),).