Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with displaying data from database from array in django
I am implementing my first website in django and I want to display a table with data taken from MySQL database. I am having a problem with sending the list of arrays to the template. I always get 500 error. This is the fragment of my views.py: if request.method == 'GET': user = request.user saved_songs = [] for idx,s in enumerate(SavedSongs.objects.raw('SELECT * FROM MGCapp_savedsongs WHERE user_id = %s', [user.id])): song_name = s.song_name genre = s.genre source = s.source date = s.date.isoformat() saved_songs.append({'idx': idx, 'song_name': song_name, 'genre': genre, 'source': source, 'date': date}) for song in saved_songs: print(song['idx']) print(song['song_name']) print(song['genre']) print(song['source']) print(song['date']) return render(request, 'saved-history.html', context = {'saved_songs': saved_songs}) There must be a problem with template, because when I print the array to the console (as you can see above), everything works fine. My template: <table class="table table-hover" style="margin-top: 20px; "> <thead> <tr> <th></th> <th>Song name</th> <th>Genre</th> <th>Source</th> <th>Date</th> </tr> </thead> <tbody> {% for song in saved_songs %} <tr> <td> {{ song['idx'] }}</td> <td> {{ song['song_name'] }} </td> <td> {{ song['genre'] }} </td> <td> {{ song['source'] }} </td> <td> {{ song['date'] }} </td> </tr> {% endfor %} </tbody> </table> -
Memory store from cloud run create error Unable to create a new session key. It is likely that the cache is unavailable
I have an application deployed on Cloud Run. It runs behind an HTTPS Load balancer. I want it to be able to cache some data using memory store service. I basically followed the documentation to use a serverless vpc connector but this exception keeps poping: Unable to create a new session key. It is likely that the cache is unavailable. I am guessing that my cloud run service can't access memorystore. On Django I have: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": f"redis://{CHANNEL_REDIS_HOST}:{CHANNEL_REDIS_PORT}/16", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "IGNORE_EXCEPTIONS": True, }, "KEY_PREFIX": "api" } } where CHANNEL_REDIS_HOST is the IP from my memorystore primary endpoint and CHANNEL_REDIS_PORT is the port. When I run this command: gcloud redis instances describe instance_name --region region --format "value(authorizedNetwork)" it returns projects/my_project/global/networks/default. Then, on the VPC network, I clicked on 'default' and then on 'ADD SUBNET'. I created my subnet with IP Address range 10.0.0.0/28. Maybe the problem comes from this step as I do not get a lot about this all IP Communication thing.. When I run this command: gcloud compute networks subnets describe my subnet purpose is PRIVATE as intended and network is https://www.googleapis.com/compute/v1/projects/my_project/global/networks/default. So I think that my memorystore instance and my … -
Weasyprint gives Fontconfig error when used with Django
I'm trying to make an application which downloads a pdf report with data from a form. The form is done by Django, the pdf by WeasyPrint. But they don't seem to work together. This works fine as code outside of Django: from weasyprint import HTML HTML(string='test').write_pdf("./report.pdf") However, when part of a Django response, like this: def result(request): buffer = io.BytesIO() HTML(string='test').write_pdf(buffer) buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='report.pdf') I get Fontconfig error: Cannot load default config file and my Django server closes. Any ideas how to solve this? I'm on Windows 10, python 3.7, installed the latest versions of Django and WeasyPrint (and their dependencies) via conda. -
Connection cannot be made using celery and django
I learnt how to send email using Django and Celery. I wrote the entire code pretty well. Then when I ran that, I faced an unusual error called ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it. I don't use any firewall or protection system in my system I'm new to this so I might even make an error in the command prompt so if there is no error please tell me what to enter correctly in the command prompt too I ran the redis server and I feel like it's working pretty fine This is the entire error I faced -------------- celery@LAPTOP-O88PS3KM v5.2.1 (dawn-chorus) --- ***** ----- -- ******* ---- Windows-10-10.0.22000-SP0 2021-11-18 19:15:24 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: djangocelery:0x2a44256a4c0 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 12 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . djangocelery.celery.debug_task . main_app.tasks.test_func . send_mail.tasks.user_send_mail [2021-11-18 19:15:24,519: INFO/MainProcess] Connected to redis://127.0.0.1:6379// [2021-11-18 19:15:24,525: INFO/MainProcess] mingle: searching for neighbors … -
referencing an ID field of a form in Views.py
I am trying to send the url of a model entry to via e-mail when my form is submitted However when I reference my form.id like so + `'(http://localhost:8000/zipherJobCards/viewJobCard/'+form.cleaned_data['id']+')',` I get the following error KeyError: 'id' Is there any right way to reference the id of an entry like this ? Please see the full send_mail function here def jobCard(request ): form = jobCardForm() if request.method == 'POST': form = jobCardForm(request.POST) if form.is_valid(): form.save() send_mail( 'ZTS JOB CARD' + form.cleaned_data['jobNumber'], 'A new job card has been loaded for ' + form.cleaned_data['customerName'] + ' with a Total Cost of ' + form.cleaned_data['totalCostOfJob'] + '(http://localhost:8000/zipherJobCards/viewJobCard/'+form.cleaned_data['id']+')', 'it.zipher@gmail.com', ['it@zipher.co.za'], fail_silently=False, ) return redirect('home') else: print(form.errors) content = {'form':form} return render(request, 'main/jobCard.html', content) -
Django DRF serializer how to get the latest object of foreignKey value
How can I grab only the latest Benchmark for each provider? Right now it grabs all of them, but I only need the latest one to be serialized. How can I achieve this? Models.py class Node(models.Model): node_id = models.CharField(max_length=42, unique=True) wallet = models.CharField(max_length=42, null=True, blank=True) earnings_total = models.FloatField(null=True, blank=True) data = models.JSONField(null=True) online = models.BooleanField(default=False) version = models.CharField(max_length=5) updated_at = models.DateTimeField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Benchmark(models.Model): benchmark_score = models.IntegerField() benchmarked_at = models.DateTimeField(default=timezone.now) provider = models.ForeignKey(Node, on_delete=models.CASCADE) Serializer.py class BenchmarkSerializer(serializers.ModelSerializer): class Meta: model = Benchmark fields = ['benchmark_score', 'benchmarked_at'] class NodeSerializer(serializers.ModelSerializer): benchmark_set = BenchmarkSerializer(many=True) class Meta: model = Node fields = ['earnings_total', 'node_id', 'data', 'online', 'version', 'updated_at', 'created_at', 'benchmark_set'] -
When i make a post and hit the "PUBLISH BUTTON" is shows a "Blog" Object is not iterable error
I have tried many ways using filter, since get tried to get a single object but it still does work. When i make a post from my admin section everything works fine but when making the post from my front end using a form it creates the posts then shows me object is not iterable "NOTE: the posts get created perfect well" but i get the iterable error and also slug does not auto populate in the frontend automatically as it does in the backend admin section. Any help would be greatly usefull and make my work faster. let me show some of my code views.py #this is for allowing user to create a new post from the frontend def blogpost(request): if request.method == "POST": form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.creator = request.user form.save() messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!') else: form = BlogPostForm() context = { "form": form } return render(request, 'blog/AddPost.html', context) #this is for listing all the blog posts def BlogList(request): posts = Blog.objects.filter(status='published').order_by('-created').values() categoriess = Category.objects.all() context = { 'posts': posts, 'categories': categoriess, } return render(request, 'blog/bloghome.html', context) # This is view for blog … -
How to forbid recreating docker containers with docker-compose up
I need your help! I started using docker this week, launched all containers for a new Django project. In this project there are several databases, python, django web server + redis, celery, etc. These all are served by separated docker containers and are launched by docker-compose up command. This is my probjem: when I type docker-compose up in the console, it starts all services. Then I need to restore my databases dumps for each database (it takes about an hour). But when I use pycharm tools for docker-compose, it recreates some containers. And also it recreates all my postgres databases with ALL MY DATA! Sometimes is doesn't recreate containers and I can do my job, but if I do any wrong move -then docker-compose erases my databases! I have tired to restore them! Is there way to protect containers from erasing, to forbid recreate my postgres containers? PS: I've also tried to export postgres containers to .tar file, but when I import it back, database insight the container is ok and container importing is faster than restoring data from sql, but metadata of docker image is different, so I can't use it. Please, give me any ideas) -
Export multiple csv file - Django
I would like to export one csv for each of my product. How can I do that? Currently it's export only the first file ... import csv products = Product.object.all() for product in products: response = HttpResponse(content_type='text/csv', charset='utf-8') response['Content-Disposition'] = 'attachment; filename=product.csv' writer = csv.writer(response, delimiter=';') writer.writerow([product.Name, product.Quantity]) return response -
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) …