Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make similar_objects() to return different lists for different models but using the same tag space
Django 3.0.7 django-taggit==1.2.0 class TagMixin(models.Model): tags = TaggableManager(verbose_name="Тэги.") # django-taggit def get_similar_objects(self): return self.tags.similar_objects() class Meta: abstract = True class Post(TagMixin, models.Model): pass class Fact(TagMixin, models.Model): pass Post here represents a post. Fac represent interesting facts. Post and Fact use the same tags. For example, if a post has a tag "Linux", then facts should also be about Linux. According to the documentation, for similar_objects() this case seems to be generic tagging (the default). Therefore this method searches tagged objects from all classes. Link: https://django-taggit.readthedocs.io/en/latest/api.html#TaggableManager.similar_objects Could you show me the most elegant solution for the following: Post and Fact share tags. get_similar_objects(self) return only what is related to the model an instance of which calls the method. -
I install django-html but when I want to change HTML to django-html in vscode I cant access it and I have plaintext
this is the txt when i select django-html �Kdjango-html-0.1.0.tar -
How to get diffrence b/w two times
I want to get the diffrence between two times as given below class Time(models.Model): start_time=models.TimeField(auto_now=False,auto_now=False,null=True) end_time=models.TimeField(auto_now=False,auto_now=False,null=True) #viewset start_time=12:00:00 end_time=15:00:00 how to get diffrence between these two times -
How to add text after a search field in Django
I have a model which takes in the Name of a Client and their phone numbers. So in the admin.py file, I added a search_field to search for clients using both the Phone number and the Name of the client. Now I want to add a text after the search bar saying "Search using Name and Phone Number". Is this possible with just the admin.py and without creating a custom filter? Please help me out with the code. TIA -
Django 3.1 - async views - working with querysets
Since 3.1 (currently beta) Django have support for async views async def myview(request): users = User.objects.all() This example will not work - since ORM is not yet async ready so what's the current workaround ? you cannot just use sync_to_async with queryset - as they it is not evaluated: from asgiref.sync import sync_to_async async def myview(request): users = sync_to_async(User.objects.all)() so the only way is evaluate queryset inside sync_to_async: async def myview(request): users = sync_to_async(lambda: list(User.objects.all()))() which looks very ugly any thoughts on how to make it nicer ? -
Django Python - created a pdf using Reportlab but can't automatically send to a model FileField entry
I can create a pdf (in this example 333.pdf) and once generated it downloads to my downloads folder and i can open the pdf successfully. I then create another form to show the last invoice created and manually click add file to upload the document to that record. Works perfectly well but my question is: "is there a way i can miss out the manual part and as soon as the invoice is created it automatically attached the pdf to the FileField for that invoice just created" Any help much appreciated models.py class Invoices(models.Model): Date = models.DateTimeField() Name = models.CharField(max_length=100, blank=True, null=True) Details = models.CharField(max_length=220) Number = models.IntegerField() document = models.FileField(upload_to='invoices/', blank=True, null=True) views.py ...... buffer = io.BytesIO() c = canvas.Canvas(buffer) c.setPageSize((page_width, page_height)) c.drawInlineImage('newlogo.png', margin, page_height - image_height - margin, image_width, image_height) c.setFont('Arial', 80) text = 'INVOICE' num=333 c.showPage() c.save() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename=str(num)+'.pdf') Then i call the following view to manually add the filename: def invoicenum(request): if request.method == 'POST': tt2 = Invoices.objects.last() form = AddInvoiceNum(request.POST, request.FILES, instance=tt2) if form.is_valid(): form.save() messages.success(request, f'Thank you that Invoice has been updated!') return redirect('frontpage-customers') else: tt2 = Invoices.objects.last() form = AddInvoiceNum(instance=tt2) return render(request, 'frontpage/addinvoice.html', {'form': form}) -
django ecommerce project geting this error AttributeError at /cart/ 'Order' object has no attribute 'orderitem_set'
class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank= True ,null = True) date_order = models.DateTimeField( auto_now_add=True) complete = models.BooleanField(default=False, null=True , blank=False) teansaction_id = models.CharField(max_length=250,null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer = customer ,complete = False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0,'get_cart_items':0} context = {'items':items , 'order': order} return render(request,'store/cart.html',context) -
What is the version of Elastic APM which is compatible with Django 1.6.11?
I am getting errors with ElasticAPM version 5.5.2 while running python manage.py elasticapm check Error: logging_config_func(self.LOGGING) File "/usr/lib/python2.7/logging/config.py", line 795, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python2.7/logging/config.py", line 577, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'elasticapm': Cannot resolve 'elasticapm.contrib.django.handlers.LoggingHandler': No module named apps Django: 1.6.11 Python: 2.7 ElastcAPM: 5.5.2 -
Javascript with Django: Not working function in Javascript
I am implementing the template of passing the id of the tuple through AJAX through the check box. But even the function behavior of JS is not working properly. My code is as follows. [sample.html] {% load static %} <html> {% block content %} <form action="{% url 'select_inf' %}" method="post" id="post_form" style="margin:20px 0 15px 0"> {% csrf_token %} <table style="width:100%; height:400px; margin-bottom:20px; border-top:solid; border-bottom:solid"> <tr> <td>Selection</td> <td>ID</td> <td>Shortname</td> </tr> {% for object in object_list %} <tr> <td><input type="checkbox" class="programChecked" value="{{object.id}}" name="{{object.name}}"></td> <td>{{object.id}}</td> <td>{{object.shortname}}</td> </tr> {% endfor %} </table> <input type="submit" style="float:right" class="btn btn-outline btn-primary pull-right" id="selectBtn" value="Click"> </form> {% endblock %} </html> {% block script_content %} <script type="text/javascript"> <!-- Working --> alert('Outside of Function'); $(function(){ $('#post_form').submit(function(e){ <!-- Not Working, I don't think it's entering this function. --> alert('Inside of Function'); e.preventDefault(); var obj_id_list = new Array(); $('input[class=programChecked]:checked').each(function() { obj_id_list.push($(this).val()); }); url = $(this).attr('action'); jQuery.ajaxSettings.traditional = true; $.ajax({ url: url, method: 'POST', data: { 'obj_id_list[]' : obj_id_list, 'csrfmiddlewaretoken':'{{csrf_token}}', 'is_ajax':true, }, }).done(function(data){ if(data.works){ alert('Complete'); var move = confirm('Do you wanna Redirect?') if(move == true){ window.location.href = "{% url 'select_inf' %}"; } else{ location.reload(); } } }); return false; }); }); </script> {% endblock %} [Current Action] Outside of function alert, of course. … -
Is there a way to receive multiple rows from a Django Subquery?
I've been running into this issue multiple times and often end up splitting the subquery from the main query. However I'd like to annotate multiple rows if multiple exist that match the conditions. more than one row returned by a subquery used as an expression Example: Having a contract where either 0, 1 or 2 people have signed it. Is there any way to annotate multiple results from a subquery? -
Django Trial Balance
Hey I want to display the trial balance on my html template. In this project i make a Ledger Creation window in which a company make a company ledger by its name. After That it fill the journal voucher form when the amount is credited/debited. Now i want to know how i can display the trial balance ( Outstanding Balance of each party). Pls help me. I share my views,models. I also Attached some screenshot. Using these i want to prepare a trial balance.[![Journal Voucher class journalVouchersView(generic.ListView): model = journalVoucher template_name = 'fa_transaction/journal_vouchers/journal_vouchers_detail.html' context_object_name = 'all_journal_vouchers' def get_queryset(self): return journalVoucher.objects.all() success_url = reverse_lazy('financial_accounting_app:journal_vouchers-detail') class journalVouchersCreate(SuccessMessageMixin, CreateView): model = journalVoucher form_class = journalVoucherForm template_name = 'fa_transaction/journal_vouchers/journal_vouchers.html' success_url = reverse_lazy('financial_accounting_app:journal_vouchers-add') success_message = "%(voucher_n)s is created successfully" class journalVouchersUpdate(SuccessMessageMixin, UpdateView): model = journalVoucher form_class = journalVoucherForm template_name = 'fa_transaction/journal_vouchers/journal_vouchers.html' success_url = reverse_lazy('financial_accounting_app:journal_vouchers-add') success_message = "%(voucher_n)s is updated successfully" class journalVouchersDelete(DeleteView): model = journalVoucher template_name = 'fa_transaction/journal_vouchers/confirm_delete.html' success_url = reverse_lazy('financial_accounting_app:journal_vouchers-detail') class CreateLedger(models.Model): name = models.CharField(max_length=200,null=False,blank=False,default="") under = models.CharField(max_length=200,null=True,blank=True,default="") pan_no = models.CharField(max_length=200,null=True,blank=True,default="") address = models.CharField(max_length=200,null=True,blank=True,default="") def __str__(self): return self.name class Meta: ordering = ['name'] -
Django server, in single or multiple instances?
I need to deploy an intranet application, and I am concerned about scalability and hardware requirements. The big question is, will I need to deploy the app to two or more server instances or will it fit in only one? Requiring two instances will increase complexity, hardware costs, maintenance, etc. So I'd prefer to handle with a single one. But I need to make "the client" confident on that only one will be enough. These are some characteristics of the application and server: Expected concurrent users, all authenticated: about 200-300. Interactive application, but no social network class. Most users (80-90%) will use mostly read-only operations (read reports, plot data) and a few write operations (add comments, save chart layouts). A few users will concentrate the write operations (create orders, heavily edit reports). There are several offices through the country. Throughput and latency are not high, and the client reports the links being heavily used already. Some heavy operations are done in the background. Others could be done that way too, if needed. We have a decent server to run it (multicpu, 64 GiB RAM), that also runs the database (MariaDB or MySQL), and other applications components (another legacy database, background … -
How to perform lazy loading or infinity loading in flutter?
I am trying to get lazy loading output with flutter. I could do lazy loading only with a generated array given by flutter as an example. But I couldn't get the same output when integrating with Rest API. How to perform lazy loading with an API in a flutter? -
How to show Monthly revenue and daily revenue in Django admin?
I have created a django Admin form my MySql database. I want to calculate monthly revenue by sum of total_amount column month wise. Similarly i want daily revenue by sum of total_amount column day wise.These is my code My models.py class Orders(models.Model): order_id = models.AutoField(primary_key=True) order_item = models.ForeignKey('Product', models.DO_NOTHING, db_column='order_item', blank=True, null=True, related_name='ordered_item') order_status = models.CharField(max_length=100, blank=True, null=True) delivery_address = models.TextField(blank=True, null=True) customer = models.ForeignKey('User', models.DO_NOTHING, db_column='customer', blank=True, null=True) quantity = models.IntegerField() rate = models.ForeignKey('Product', models.DO_NOTHING, db_column='rate', blank=True, null=True) date_time = models.DateTimeField() # total_amount = models.DecimalField(blank=True, null=True,decimal_places=2,max_digits=10) @property def total_amount(self): rate = Product.objects.get(pk=self.order_item.product_id) total_amount = rate.price * self.quantity return total_amount class Meta: managed = False db_table = 'orders' class Product(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=100, blank=True, null=True) image = models.CharField(max_length=100, blank=True, null=True) product_info = models.TextField(blank=True, null=True) brand = models.CharField(max_length=100, blank=True, null=True) packing = models.CharField(max_length=100, blank=True, null=True) price = models.DecimalField(blank=True, null=True,decimal_places=2,max_digits=10) store1_stock = models.IntegerField(blank=True, null=True) store2_stock = models.IntegerField(blank=True, null=True) store3_stock = models.IntegerField(blank=True, null=True) store1_disc = models.CharField(max_length=100, blank=True, null=True) store2_disc = models.CharField(max_length=100, blank=True, null=True) store3_disc = models.CharField(max_length=100, blank=True, null=True) min_purchase_limit = models.IntegerField(blank=True, null=True) max_purchase_limit = models.IntegerField(blank=True, null=True) category = models.ForeignKey(Category, models.DO_NOTHING, db_column='category', blank=True, null=True) sub_category = models.ForeignKey('Subcategory', models.DO_NOTHING, db_column='sub_category', blank=True, null=True) class Meta: managed = False db_table = 'product' def __str__(self): … -
I am trying to create a download view and url for images using django and rest framework. Downloads but not as an image
**class ImageDownloadView(APIView): def get(self, request, *args, kwargs): img = Wallpaper.objects.get(id=1) full_path = "C:/devloy/photography_sheikha_backend/sheikha_photography%s" % img.image_2.url Wrapper = open(full_path, 'r', errors='ignore') response = HttpResponse(Wrapper,content_type='image/jpg') response['Content-Disposition'] = "attachment; filename=%s" % img.title return response -
How to send correct request via Postman to Django REST framework
I have customized the user model in order to suit my customer's needs and the method I used is to utilize Django REST framework. Because I am working with a frontend engineer, I must know the correct form of request to send to the server. So, to make sure my api works with the request, I took a look at the 'raw data' section of the REST framework page and implemented the same format into the Postman. The former is the REST framework page and the latter is my postman request. However, I keep gettings 500 error, which I assume is coming from the malformed request data. So I tried to take a look at the request.body using 'import pdb; pdb.set_trace()' everywhere, but the code execution would not stop anywhere I put pdb. Below are my codes. user/views.py from rest_framework import generics from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from user.serializers import UserSerializer, AuthTokenSerializer class CreateUserView(generics.CreateAPIView): """Create a new user in the system""" serializer_class = UserSerializer class CreateTokenView(ObtainAuthToken): """Create a new auth token for user""" serializer_class = AuthTokenSerializer renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES user/serializers.py from django.contrib.auth import get_user_model, authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): … -
Django ORM filter on bool field not permitted
i have my django models: class p_linea(models.Model): l_name = models.CharField(max_length=100, verbose_name="Linea") l_pubblica = models.BooleanField(default=False, verbose_name="Pubblica") l_note = models.TextField(null=True, blank=True, verbose_name="Note interne") class Meta: verbose_name = "Linea" verbose_name_plural = "Linee" def __str__(self): return '%s' % ( str(self.l_name)) class p_catlinea(models.Model): p_lid = models.ForeignKey(p_linea, on_delete=models.CASCADE, verbose_name="Linea") p_cid = models.ForeignKey(p_catl, on_delete=models.CASCADE, verbose_name="Categoria") l_note = models.TextField(null=True, blank=True, verbose_name="Note interne") dt = models.DateTimeField(auto_now=True, verbose_name="Upload") class Meta: indexes = [ models.Index(fields=['p_cid','p_lid']), ] verbose_name = "Linea/Categoria" verbose_name_plural = "Linea/Categoria" def __str__(self): return '%s' % ( str(self.p_cid)) now in my views.py i try to filter p_catliea baset on the fact that p_linea.l_pubblica is True, i try: ... p_cl = p_catlinea.objects.all().select_related() for x in p_cl: if x.p_lid.l_pubblica: try: l_lincat[str(x.p_lid)]['cat'] = get_cat(x.p_lid_id) except KeyError: l_lincat[str(x.p_lid)] = {'cat': get_cat(x.p_lid_id),} but i got error: 'bool' object is not callable even if i di x.p_lid.l_pubblica == True i got the same error. How can i filter my data based on True or Fale of related table field? So many thanks in advance -
Is there a Django admin widget for ordered many-to-many relationship with extra fields?
Is there a package to install or an easy way for me to code something similar to the below mock-up for a widget for the Django admin interface? +--+-----------------+-+-+ | #|Record Name |p|n| +--+-----------------+-+-+ |01|A record |✓|x| |02|Some other record|x|x| |03|A record |x|✓| |04|Take the A train |✓|✓| +--+-----------------+-+-+ Noteworthy features: Records may appear multiple times Order of the records matters (I presume the numbering column would be auto-populated and records would be moved by dragging or up/down arrows to the side of the table) The two checkboxes at the end of the table are central to the design: the whole project doesn't make much sense without them being inline like this A potential base for the solution It gets the sorting right but their documentation recommends that you use a normal Django m2m field with your own through model rather than adding additional fields to a sortedm2m because the extra fields won't play nice with automatic migration. However, this project relies on transient sqlite databases—does this make the lack or automatic migrations more or less of an issue compared to running it in a "real" database? Project Context What I am considering is using the Django admin suite as … -
django html_form' referenced before assignment
I'm trying to create a CRUD in Django using json Ajax , but in my views I'm getting an error that " UnboundLocalError at /orderlist/create_order/ local variable 'html_form' referenced before assignment " views.py def create_order(request): initial_date = { 'status':"In Progress" } form = OrderForm(request.POST or None, request.FILES or None,initial=initial_date, user=request.user) if request.method == 'POST': if form.is_valid(): order = form.save(commit = False) order.user = request.user; order.save() form = OrderForm(user=request.user) messages.success(request, "Successfully created") return redirect('/orderlist') context = {'form':form} html_form = render_to_string('accounts/templates/order_form.html', context, request=request, ) return JsonResponse({'html_form': html_form}) -
When to check for new notifications Django-notifications w/ React Frontend
I have set up django-notifications-hq so when I send a chat message, a new < Notification Object > is created, which references the recipient, a < User object >. I have set up a backend API using DRF, and have Redux ready to go. Currently I planned on checking for new notifications every 5 seconds or so, but this is obviously not scalable. Is there a way I can go about calling the checkNotifications action from the recipient when the < Notification object > is created? Get Notification Action: export const getNotifications = () => (dispatch, getState) => { const config = tokenConfig(getState); // if (username) { // config.params["username"] = username; // } axios .get(`/api/notifications/`, config) .then((res) => { dispatch({ type: GET_NOTIFICATIONS, payload: res.data, }); }) // .catch((err) => // dispatch(returnErrors(err.response.data, err.response.status)) // ); .catch((err) => console.log(err)); }; -
Paytm Payment Integration in Django
I am facing a weird issue with Paytm Payment Integration in Django3. While the successful transaction flow is smooth. Failure cases are sending GET parameters to my django application like this on the callback URL: retryAllowed=false&errorMessage=Your%20payment%20has%20been%20declined%20by%20your%20bank.%20Please%20try%20again%20or%20use%20a%20different%20method%20to%20complete%20the%20payment.&errorCode=227 Some help is appreciated. -
Inline formset missing filefield value
I am having issues using django Inlineformsets. I have 2 models named Projects and projectFiles, Projects being the parent model and projectFiles, the child. models.py class Projects(models.Model): project_name = models.CharField(max_length=100) class projectFiles(models.Model): projectName = models.ForeignKey('Projects',on_delete=models.CASCADE) p_file = models.FileField(upload_to='Files',null=True,blank=True) remark = models.CharField(max_length=500,null=True,blank=True) my formset is the one below, projectfilesFormSet = inlineformset_factory(Projects,projectFiles,fields=['p_file','remark'], extra=1,labels={'p_file':'File',}, widgets = { 'p_file' : forms.FileInput(attrs={'class':'form-control-file'}), 'remark' : forms.TextInput(attrs={'class':'form-control'}), }) and my view is the one below, def fileUpload(request,pk): r_project = Projects.objects.get(pk=pk) if request.method == 'POST': formset = projectfilesFormSet(request.POST,request.FILES,instance=r_project) if formset.is_valid(): formset.save() return redirect('projects:file_upload',pk=r_project.id) formset = projectfilesFormSet(instance=r_project) return render(request,'projects/files_upload.html',{'formset':formset}) The formset saves the data, but i am unable to see the value for the p_file field along with other field values.Now, if i check the database,the field has a value. Somehow i am unable to display it in my template. my template is, <form class="forms-sample" action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} <div class="row mt-3"> <div class="col-md-4">{{field.label_tag}}</div> <div class="col-md-8">{{field}}</div> </div> {% endfor %} <hr> {% endfor %} <button type="submit" class="btn btn-primary mr-2">Save</button> </form> I doubt that i missed something in the template, but … -
Users not writing to database (Postgresql)
When I create a user with my custom user model I cannot sign in. It just keeps telling me Please enter a correct email and password. Note that both fields may be case-sensitive. I thought I should check if I can see my test user in the db. I know only staff accounts can login to the admin but I'm using a different login form. If I'm not mistaken it looks like there aren't any users in my database. myproject=# \dt accounts_user List of relations Schema | Name | Type | Owner --------+---------------+-------+------------------ public | accounts_user | table | myprojectuser (1 row) Here's my user model: from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, company, phone, is_active=True, is_admin=False, is_staff=False, is_dealer=False, password=None): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") if not first_name: raise ValueError("Users must have a first name") if not last_name: raise ValueError("Users must have a last name") if not company: raise ValueError("Users must have a company") if not phone: raise ValueError("Users must have a phone number") user_obj = self.model( email = … -
Django FileField path in form change to absolute
I my django project i have a models like thisone: class v_candidatura(models.Model): c_data = models.DateTimeField(auto_now=True, verbose_name="Upload") c_tit = models.CharField(max_length=5, verbose_name="Titolo") c_sur = models.CharField(max_length=100, verbose_name="Cognome") c_name = models.CharField(max_length=100, verbose_name="Nome") c_dob = models.CharField(max_length=50, verbose_name="Data di nascita") c_res = models.CharField(max_length=200, verbose_name="Residenza") c_email = models.CharField(max_length=100, verbose_name="Email") c_mansione = models.CharField(max_length=50, verbose_name="Mansione") c_en = models.CharField(max_length=50, verbose_name="Conoscenza EN") c_de = models.CharField(max_length=50, verbose_name="Conoscenza DE") c_pres = models.TextField(null=True, blank=True, verbose_name="Presentazione") c_cv = models.FileField(upload_to='villagemma/static/docs', max_length=254, validators=[FileExtensionValidator(['pdf']),validate_fsize], verbose_name="CV") class Meta: verbose_name = "Candidature" verbose_name_plural = "Candidature" def __str__(self): return str(self.c_sur) now in my view i save() data from a form in my model, plus cv file in c_cv field, all done. When i open django admin and check for inserted data i find my cv link: but when i click on link i find that before the correct path i got all django admin path, for example in this case get: http://127.0.0.1:8000/admin/personale/v_candidatura/4/change/villagemma/static/docs/Prenotazione__ParkinGO.pdf that is wrong insetad: http://127.0.0.1:8000/villagemma/static/docs/Prenotazione__ParkinGO.pdf How can i point to absolute link in django admin filefield path in django Admin? So many thanks in advance -
Django Javascript Static File Unexcepted Token % for Ajax URL
Initially I struggled with rendering my JavaScript file through the static element in Django I finally was able to do this: <script src='{% static "app_name/js/index.js" %}'></script> In the above JavaScript, I have AJAX wherein the url is in this format: url:{% url 'urlname' %}, In the browser console, I get the following error which points to the above AJAX line: Uncaught SyntaxError: Unexpected token '%' It was working fine when the JavaScript was in the same page as the template. But now I am trying to separate the JavaScript from the template and this error occurs. How do I tell my JavaScript file that this is a valid Django code?