Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Translation (i18n) for FormView based class's attribute
I'm in the process in making my django app available in multiple languages. I've managed to do it everywhere, for every string of character, but the only point in failure is translating my FormView based classes' attribute, like a success_message. Here is an example: from django.utils.translation import gettext as _ class MyModelDelete( LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, DeleteView ): model = MyModel success_message = _("Successfully deleted MyModel") def delete(self, request, *args, **kwargs): messages.success(self.request, _("This is an example")) messages.success(self.request, self.success_message) return super(MyModelDelete, self).delete(request, *args, **kwargs) Here the "This is an example" will correctly be translated, but not the success_message as show the following screenshot: http://i.imgur.com/98h5diP.png How to translate such attributes ? Thanks PS: ofc, I have a translation for both strings in my .po files. -
Django OneToOne fields conflicting when creating both instances in same view
I'm sure I'm missing something here. I do have two models, Foo and Bar like so class Foo(models.Model): name = models.OneToOneField(Bar) class Bar(models.Model): name = models.OneToOneField(Foo) Now I have to create new instances for both of them which will be mapped 1-1. Creating an instance, it requires me to map name to the other instance which doesn't exist yet. How to handle with this? Is there a way to create an empty instance beforehand or s.th.? foo_instance = Foo(name=bar_instance) bar_instance = Bar(name=foo.instance) # won't work .. -
How can I use integer field as a foreign key in Django?
You can see my files below. I have two models: Order and OrderedBook. When a user makes an order, I create a few OrderedBook instances(its number depends on how many books the user ordered). In addition, OrderedBook has a field 'orderNumber' and it's a foreign key. However, I want it to be an integer, but Django requires an Order instance. How can I implement it? models.py class Order(models.Model): orderNumber = models.AutoField('Номер замовлення', primary_key=True) userFirstName = models.CharField('Ім\'я', max_length=32) userLastName = models.CharField('Прізвище', max_length=32) userPatronymic = models.CharField('По-батькові', max_length=32) userEmail = models.EmailField('Електронна адреса', ) userPhone = models.CharField('Номер телефону', max_length=13, validators=[phoneNationalFormatValidator, phoneLessNumbersValidator, phoneValidFormatValidator]) delivery = models.CharField('Доставка', choices=DELIVERY, max_length=10, default='NovaPoshta') date = models.DateTimeField(default = timenow) deliveryAddress = models.CharField(max_length=128, default='') def __str__(self): return f"Замовлення №{self.orderNumber}" class OrderedBook(models.Model): orderNumber = models.ForeignKey(Order, on_delete=CASCADE, to_field='orderNumber') user = models.ForeignKey(CustomUser, on_delete=CASCADE) book = models.ForeignKey(Book, on_delete=CASCADE) def __str__(self): return f'Замовлення №{self.orderNumber} - {self.book}' views.py def cart(request): items = CartItem.objects.filter(user=request.user) total = sum(x.book.price for x in items) if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() theSameForm = form.save() # after purchase delete all ordered books from user's cart and reduce their count by 1 for cartItem in items: book = Book.objects.get(ISBN=cartItem.book.ISBN) book.number -= 1 book.save() newOrderedBook = OrderedBook.objects.create( orderNumber = theSameForm.pk, # … -
Celery Duplicate Tasks which has multiple task_args are not getting revoked
I have written following method to revoke duplicate celery tasks which has same task name and task arguments. from celery import current_app from celery.utils.log import get_task_logger from django_celery_results.models import TaskResult def revoke_duplicate_tasks(task_name, task_args=[], request_id=None): # Get a list of task ids which are initiated for task_args and are in # pending/received/started state celery_logger = get_task_logger(__name__) task_args = '"' + str(tuple(task_args)) + '"' celery_logger.info(f'Current Task Args - {task_args}') celery_logger.info(f'Request ID - {request_id}') duplicate_tasks = list(TaskResult.objects.filter( task_name=task_name, status__in=['PENDING', 'RECEIVED', 'STARTED'], task_args=task_args ).exclude( task_id=request_id ).values_list('task_id', flat=True)) celery_logger.info(f'revoking following duplicate tasks - {duplicate_tasks}') current_app.control.revoke(duplicate_tasks, terminate=True, signal='SIGKILL') If I run this method via django shell then duplicate_tasks has list of task_id and those tasks get revoked, but if I run same piece of code in celery as a service then duplicate_tasks is empty list and tasks are not getting revoked. Django - 3.2.8 Celery - 5.1.2 Flower - 1.0.0 I have been at this for a long while now, so any pointers would be really great help. -
Display choicefield in admin as input field
I have a database of maybe 100 users that have each 5-10k products linked to them. In the admin panel I can do checkup on a function to display those products and this works just fine, but loading that page is really slow because of the many products. So what I want to do is replacing it with a regex or at least a number input field that does not preload all the products: models: class Store(models.Model): name = models.CharField("name", max_length = 128) city = models.CharField("city", max_length = 30, null = True, blank = True) store_id = models.IntegerField("store id", unique = True) user = models.OneToOneField(User, on_delete = models.CASCADE, ) class Product(models.Model): data = models.JSONField() store = models.ForeignKey(Store, on_delete = models.CASCADE) number = models.PositiveIntegerField() admin: class ProductTabularInline(admin.TabularInline): model = Product class StoreAdmin(admins.ModelAdmin): inlines = [ProductTabluarInline,] In the admin panel right now I have a TabularInline for Product which displays all the products when clicking on store as a dropdown (Which means they have to be preloaded first obviously). Is there any simple way I could change this to a number Input (number key of the product, but even pk would help me), or even better regex? Can I just do this … -
Openning a PostGIS shapefile using django in web app
I created a django app that connects to Geoserver and PostGIS database. The intention is to create a web app using Leaflet, django and PostGIS connection. I add the data to PostGIS and import do django. However everytime appears these errors: Object 'parsererror' Error: getJson was not called at Function.error (jquery.min.js:2) at e.converters.script json (jquery.min.js:2) at jquery.min.js:2 at l (jquery.min.js:2) at HTMLScriptElement.i (jquery.min.js:2) at HTMLScriptElement.dispatch (jquery.min.js:2) at HTMLScriptElement.v.handle (jquery.min.js:2) Then it gives me this error: Uncaught ReferenceError: getJson is not defined In the django (index.html) the shapefile is requested to Geoserver as WFS, as this: var wfsLayer_solos = L.Geoserver.wfs("http://localhost:8080/geoserver/wfs", { layers: "gic:solos1_2_4326", style: { color: "black", fillOpacity: "0", opacity: "0.5", }, onEachFeature: function (feature, layer) { layer.bindPopup('<pre>'+JSON.stringify(feature.properties,null,' ').replace(/[\{\}"]/g,'')+'</pre>'); }, }); -
putting a Django website on production using sqlite data base
hey I'm currently working on a website (Photo selling services) and now I wanna deploy it on a public host, I didn't change the database and I'm using Django's SQLite as my database, Is it gonna be a problem or it's fine? and also I'm handling the downloads with my views and template and the files (photos) will be downloaded from my database and I wanted to know do I need one host for my application and another for putting my photos in? or I can just run the whole website on one host without a problem ( same as I'm running it on my local host). -
I have to change db everytime when project updated What Should I do?
My DB is Postgres and Code in Django, I live a project daily but I want old DB in a new project which has only just some updates in it but If I don't Update it It shows migration error and if I use --fake then on that page it will show similar error 'Programming Error Column Does Not Exist' I tried each and every way pls help me. Thanks -
How to reference ForeignKey Fileds on form submit
I currently have a customers model and a job card model that are connected by some of the customer details. I have created a foreign key on the customer name field so that the user can enter all the customer details by just selecting a pre-added customer, How would I be able to reference this when saving the job card form. it would need to be based on what the user had selected for the customerName field and then it would need to fetch the contact details and address details from the "customer" model. Please see the following code : Models.py: class newCustomersClass(models.Model): customerName = models.CharField("Customer Name",max_length=50 , blank=True) addressStreetNo = models.CharField(max_length=50 , blank=True) addressStreet = models.CharField(max_length=50 , blank=True) addressSuburb = models.CharField(max_length=50, blank=True ) addressCity = models.CharField(max_length=50, blank=True ) contact = models.CharField(max_length=50, blank=True ) mail = models.CharField(max_length=50, blank=True ) CellNo = models.CharField(max_length=50, blank=True ) customerClass = newCustomersClass.objects.all() customers = [] for row in customerClass: rdict = {} rdict.customerName = row[0] customers.append(rdict) class jobCardsClass(models.Model): customerName = models.ForeignKey(to=newCustomersClass, on_delete=models.DO_NOTHING) addressStreetNo = models.CharField(max_length=50 , blank=True) addressStreet = models.CharField(max_length=50 , blank=True) addressSuburb = models.CharField(max_length=50, blank=True ) addressCity = models.CharField(max_length=50, blank=True ) contact = models.CharField(max_length=50, blank=True ) mail = models.CharField(max_length=50, blank=True ) CellNo = models.CharField(max_length=50, … -
python, django, display the correct field name by FK, linked tables
models.py file #create class roles, id, portal_name, role_name class Roles(models.Model): portal_name = models.CharField(_('Portal name'), max_length=100) role_name = models.CharField(_('Role_name'), max_length=50) #create permission for roles class RolePermission(models.Model): module_name = models.CharField(_('Module name'), max_length=100) module_delete = models.BooleanField(default=False, help_text="Delete module. Default false, can't delete") module_edit = models.BooleanField(default=False, help_text="Edit module. Default false, can't edit") module_create = models.BooleanField(default=False, help_text="Create module. Default false, can't create") module_submit = models.BooleanField(default=False, help_text="Submit module, Default false.") module_role_id = models.ForeignKey('Roles', on_delete=models.CASCADE) my admin.py file @admin.register(RolePermission) class RolePermissionAdmin(admin.ModelAdmin): list_display = ('module_name', 'module_role_id_id', 'module_delete', 'module_edit', 'module_create', 'module_submit') as in the column display information on role_name from table roles, used Foreign Key -
Can I remember instance of object?
I'm using django-channels and aiortc, I want to create server to peer connection as WebRTC. In my case, if client send the new-peer action, then server send the offer. And after client receive the offer, client send the answer as new-answer action. But server can't remember peer, so can't setRemoteDescription. Of course I know server don't remember, but how do I deal with situations where server need to remember instances like mine? I also looked for session variables, but it seems that only simple values can be stored, and it doesn't seem to have anything to do with the instance. Please provide helpful documents or solutions related to this. consumers.receive method: async def receive(self, text_data): receive_dict = json.loads(text_data) message = receive_dict['message'] action = receive_dict['action'] if (action == 'new-peer'): # Create Offer peer, offer = await create_offer() receive_dict['message']['sdp'] = offer receive_dict['action'] = 'new-offer' receive_dict['message']['receiver_channel_name'] = self.channel_name await self.channel_layer.send( self.channel_name, { 'type': 'send.sdp', 'receive_dict': receive_dict } ) return None elif (action == 'new-answer'): await peer.setRemoteDescription(receive_dict['message']['sdp']) receiver_channel_name = receive_dict['message']['receiver_channel_name'] receive_dict['message']['receiver_channel_name'] = self.channel_name await self.channel_layer.send( receiver_channel_name, { 'type': 'send.sdp', 'receive_dict': receive_dict, } ) return None else: raise ValueError('Unexpected action value'); create_offer function: async def create_offer(): pc = RTCPeerConnection(RTCConfiguration(iceServers)) rtsp_video = MediaPlayer(rtsp_test_url) relay = MediaRelay() … -
I am getting only one object in post method inside APIView of django rest framework even if I used ScrapyItem.objects.all(). Anyone knows why
##Any one knows how to fix this. I am getting only one object in post method inside APIView of django rest framework even if I used ScrapyItem.objects.all(). Anyone knows why## class ScrapyViewSet(APIView): def get(self, request, format=None): snippets = ScrapyItem.objects.all() serializer =ScrapySerializer(snippets, many=True) return Response(serializer.data) def post(self, request): snippets = ScrapyItem.objects.all() domain=request.data['domain'] print(domain) for i in snippets: print(i) if i.domain==domain: return Response({"status": "success", "data": str(i.data)}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": 'error'}, status=status.HTTP_400_BAD_REQUEST) -
Problems with connecting amplitude http api to python django
Did someone have experience with amplitude analytics ? And can you connect http api of amplitude analytics with python django or simple python ? Please help me. Thank you in advance #analytics #python #django #amplitude -
Array of images from .js file not showing in Django template
I am building a website and I have an image-slider.js which renders an array of images var arr=['images/1.jpg','images/2.jpg','images/3.jpg','images/4.jpg','images/5.jpg']; //an array of image sources var pos=0; then on my template I have <div id="slider"></div> The images do show on my templates I get the 404 I have tried all method I google but none is working -
Filtering data from database in django
I need to select a specific category from appointments to display on my table. I am only displaying all the records from the database. I have 3 categories; plumbing, electrical and cleaning {% for appointment in appointments %} <td>{{appointment.worker}}</td> <td>{{appointment.category}}</td> <td>{{appointment.date_created}}</td> <td>{{appointment.status}}</td> <td><a class="btn btn-sm btn-danger" href="{% url 'delete_appointment' appointment.id %}">Delete</a></td> </tr> {% endfor %} -
Export only list_display colums with verbose_name's?
Hello I am newbie for django so I have basic question. In my admin class I added ExportMixin and I want to save excel file with my list_display colums and verbose names. Not id colum or lets say I have status it says keep going or not doing but I show 0 -1 under the status. I am still looking for the answer please help me :) MyCode: @admin.register(Ico) class IcoAdmin(ExportMixin, BaseAdmin): list_display = ( 'account', 'pair', 'amount', 'ico_situation', 'expire_date', 'price', 'token_amount', 'reference_user', 'get_reference_user_income') list_filter = ('account', 'account__is_bot') search_fields = ('account_id', 'wallet_id', 'ico_situation') raw_id_fields = ('account', 'pair', 'wallet', 'reference_user') My Excel table : id account wallet pair amount token_amount final_token_amount expire_date status ico_situation price reference_code reference_user 152 111 789 12 100 400 0 2022-03-17 1 1 0,25 151 111 789 12 100 200 0 2021-11-17 1 0 0,5 150 111 789 12 100 200 0 2021-11-17 1 0 0,5 2 149 111 789 12 100 200 0 2021-11-17 1 0 0,5 148 111 789 12 100 200 0 2021-11-17 1 0 0,5 2 147 111 789 12 100 200 0 2021-11-17 1 0 0,5 146 111 789 12 100 200 0 2021-11-17 1 0 0,5 2 Table I want: (https://ibb.co/8YpQ0S1) … -
How to set query parameters in Django and dynamically update charts
I am new to Django and this is taking a lot of my time. Any help would really be appreciated. I am using chart js to render charts in my HTML and I have a date filter in the HTML template, which I will use as a filter to display data in charts. I have data in the backend which needs to be displayed dynamically in the front end upon selecting the date. My backend code takes 'from' and 'to' dates from the request. How do I pass the selected date ranges as query params to the request, so that request.GET['from'] uses my start date and update my chart in the HTML with results dynamically -
pagination in django rest framework not working
I have written CustomPagination from drf in a separate file in my project which is like this. class ProductPageNumberPagination(PageNumberPagination): page_size = 1 class CustomPagination(PageNumberPagination): def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'page_size' : 15, 'results': data }) Now I am inheriting it in my view like this: class CouponView(APIView,CustomPagination): permission_classes = [AllowAny] # pagination_class = CustomPagination def get(self,request,pk = None,*args,**kwargs): id = pk if id is not None: abc = Coupons.objects.get(id=id) serializer = CouponSerializer(abc) return serializer.data else: abc = Coupons.objects.all() serializer = CouponSerializer(abc,many=True) return Response(serializer.data,status=200) However, the above code is not working. If I had imported default PageNumberPagination it will work but why inheriting my custom class is not working is my question. Seems like only the default class be inherited and not the custom-defined one. -
django.db.utils.OperationalError: no such table: django_session
Premise: I'm a starter[Plz be kind and patient] When i try to run commands in the terminal like: python manage.py makemigrations audioma_manager or python manage.py runserver or python manage.py migrate or python manage.py --run-syncdb where audioma_manager is the name of my project I tried also with the name of my app I get this excetion code, I searched lots on the net but any kind of solution works with my problem: Traceback (most recent call last): File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: django_session The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 423, in check databases=databases, File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 13, … -
Dajngo forms placeholder and mask: data correctly saved in database but wrongly displayed at screen
I have an issue with formatting floatfield in Django. I set placehodler and data-mask: 000.0 When I enter data infields, it is correctly save in database but when I display form, it is wrongly displayed. For example, I enter '078.1' for weight. 78.1 is saved in database but when I open form, 781 is displayed. It seeems that 'missing' 0 at the beggining of floatnumber make it slice in the left and I lost comma models.py inc_poi = models.FloatField('Poids (kg)', null=True, blank=True) forms.py self.fields['inc_poi'] = forms.FloatField(label = 'Poids (kg)',widget=forms.TextInput(attrs={'placeholder': '000.0','data-mask':'000.0'}),required=False,disabled=DISABLED) -
Am following tutorials on Build powerful and reliable Python web applications from scratch by Antonio. But am stuck at Registering the image model [closed]
Even after i use the right password I still get that error -
Displaying all foreign keys a links
Is it possible to configure Django admin, so all foreign keys be displayed in the list view as links? Clicking on such a link should open the view for the related object. The closest I could find is list_display_links, which is actually unrelated, because it links to the current object... -
Enable editing a field in Django admin's list view
Consider a model that stores application forms. I would like to use Django admin to quickly view applications and change their status. I would like to be able to change the status of an application right in the view listing all the applications without having to open each application for editing. So, is it possible to make a field editable right in the admin list view? -
How to return sum according to date range in django?
It'd be really nice if someone could help me with this. I've stuck here. I'm able to do this manually but how to do according to user input. Payment.objects.filter(created_by=42, mode='cash', created_at__range=["2021-11-01", "2021-11-04"]).aggregate(Sum('amount')) Here created_by and date_range I'm sending in url like this : http://127.0.0.1:8000/api/v1/registration/?created_by=42&start_date=2021-06-06&end_date=2021-11-18 so the id created by and date_range will always change. And according to change the sum will return. My Model : class Payment(TimestampedModel): customer_visit = models.ForeignKey( CustomerVisit, on_delete=models.CASCADE, null=True, related_name="customer_payments" ) mode = models.CharField(choices=PAYMENTCHOICES, max_length=25) amount = models.FloatField() ref_no = models.TextField(null=True) bank = models.ForeignKey( "BankDetails", on_delete=models.CASCADE, null=True, related_name="payment_bank" ) is_settlement = models.BooleanField(default=False) created_by = models.ForeignKey("Employee", on_delete=models.DO_NOTHING, null=True,related_name='payment_created_by') updated_by = models.ForeignKey("Employee", on_delete=models.DO_NOTHING, null=True,related_name='payment_updated_by') My View : class UserWiseCollectionView(ListAPIView): permission_classes = [ IsAuthenticated, ] pagination_class = CustomPagination model = CustomerVisit serializer_class = UserWiseCollectionSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['created_by'] def get_queryset(self): start_date = self.request.query_params.get("start_date") end_date = self.request.query_params.get("end_date") emp_id = self.request.query_params.get("emp_id") items = self.model.objects.all() if start_date and end_date: items = items.filter( created_at__range=[start_date, end_date] ) if emp_id is not None: items = items.filter(phelebotomist_id = emp_id) return items -
Django: Load JSON into Bootstrap table with AJAX function + Missing Data
I want to create a simple application that can discover data from a database (a live program) with Django. One of the features is to display the list of tables. A response API that contains the list of table names from a database has been created: { "message": "success", "results": [ { "schema": "public", "table": "actor" }, { "schema": "public", "table": "actor_info" }, { "schema": "public", "table": "customer_list" }, { "schema": "public", "table": "film_list" }, .... ] } Then, I want to display the data (from API) in a bootstrap table by creating an AJAX function. This is my HTML file (full code is here): ... <div class="table-responsive"> <table class="table table-sm" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Schema</th> <th>Table Name</th> </tr></thead> <tbody id="divBody"></tbody> </table> </div> ... This is my AJAX function (Currently, I used the GET method. I want to change into POST method later): <script> $(document).ready(function () { BindTables(); }); function BindTables(){ $.ajax({ type:"GET", dataType: "JSON", url: "http://127.0.0.1:8000/api/v1/table/", success: function(data){ console.log("It's success"); console.log(data.results) var structureDiv = ""; for (let i=0; i < data['results'].length; i++){ structureDiv += "<tr>" + "<td>" + data['results'][i].schema + "</td>" + "<td>" + data['results'][i].table + "</td>" + "</tr>" } $("#divBody").html(structureDiv); } }); } </script> Currently, I can …