Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - pass data from basic HTML form into model
I have created a simple app in Django using some tutorials, but it became very usefull and also scaled a lot. What i have is a basic HTML table - prefilled with data from Model A. At the end of the table there is Submit button, which just use some javascript to prompt a print window (to save the table[page] as PDF basically) What i would like to do, is that when i press the Button to print, i would also pass some data from the table for example ModelA name and adress into a ModelB - which would serve as an statistic. However i have used for this a simple tutorial, and therefore to display the table i used "DetailView" in views.py. This is my views.py file class PrinterDetailView(DetailView): model = Printer template_name = 'printer_detail.html' Is it possible to achieve this without redoing the whole site? i Found some people searching for simillar answers, but from that it seemed like i would have to redone whole app.. Thanks for your input! -
Sum total value for all items
I have a query set that contains a number of transactions for a particular product. transactions = Transaction.objects.filter(product__product_name_id = item.id) Within this queryset contains a number of fields. product amount price transaction_date I need to calculate the totals of the values in the amount fields. The current query set is returning 2 amounts from 2 `transactions' Would it be sensible to loop through each transaction and add it to a list of something? or is there a better way? list = [] for item in transactions: amount = item.amount list.append(amount) Thanks -
how to exclude fields that are in one depth level with DRF?
how to exclude fields that are in one depth level in django rest framework? I want to remove id field in testPieces and resultTestsList. this is my API: my serializer: class Test_Serializer(serializers.ModelSerializer): class Meta: model = Test_1 exclude = ["id"] depth = 3 my models: class Test_pieces_1_question(models.Model): question = models.CharField(max_length=3000) yesScore = models.IntegerField() noScore = models.IntegerField() class Result_tests_list_1(models.Model): text = models.CharField(max_length=3000) score = models.IntegerField() unicode = models.CharField(max_length=500) class Test_1(models.Model): name = models.TextField(max_length=3000) category = models.CharField(max_length=500) time = models.CharField(max_length=500) testPieces = models.ManyToManyField(Test_pieces_1_question) resultTestsList = models.ManyToManyField(Result_tests_list_1) my view: class Whole_test(mixins.ListModelMixin, generics.GenericAPIView): queryset = Test_1.objects.all() serializer_class = Test_Serializer filter_backends = [DjangoFilterBackend] def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) thanks! -
DJANGO API - Background API
I have a requirement which involves downloading a large csv, checking for some information, and mailing somebody. And I can't write a sync API. I was looking for ways to write a API that returns a response and starts running this function server side. Can you suggest me a way to do it in DJANGO? Thanks. -
confluent-kafka-python save to database
I have a Djnago project and I'm trying to save objects to database inside of kafka consumer. I get records from kafka like this: def sync_product_from_kafka_consumer(): topic = PRODUCT_KAFKA_TOPIC_NAME schema_str = """*some_json*""" json_deserializer = JSONDeserializer(schema_str, from_dict=dict_to_product) string_deserializer = StringDeserializer('utf_8') consumer_conf = {'bootstrap.servers': KAFKA_SERVERS, 'key.deserializer': string_deserializer, 'value.deserializer': json_deserializer, 'group.id': 'myproject.dev.group-k8s-dev', 'auto.offset.reset': "earliest"} consumer = DeserializingConsumer(consumer_conf) consumer.subscribe([topic]) while True: msg = consumer.poll(1.0) if msg is None: continue product = msg.value() if product is not None: save_product(product) # sync_to_async(save_product)(product) consumer.close() def save_product(product): defaults = { *some_dict* } Product.objects.update_or_create(id=product.id, defaults=defaults) But after execute this code I get exception: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How do I fix it? Thanks for any help! -
The view Project.views.profile didn't return an HttpResponse object. It returned None instead
def profile(request): if request.user.is_authenticated: pass else: return render(request, 'profile.html') I have this code -
How do I get only non deleted items from many to many field where both the table have soft deletion on them in django?
I have the following tables class B(mixins.BaseModel, OriginPublicIdMixin, mixins.SoftDeletionModel): # has soft deletion with soft deletion manager class C(mixins.BaseModel, mixins.SoftDeletionModel: # has soft deletion, with soft deletion manager class A(mixins.BaseModel, mixins.SoftDeletionModel): d = models.ManyToManyField("B", related_name="a", through="C") Now when I do a = A.filter(pk='some_id') result = a.d.all() The result contains entries for which B is non-deleted and C is deleted/non-deleted. I want to get only those entries, for which both B and C are non deleted. In what way can I do that without having to filter again by C is not None I have already tried using use_for_related_fields = True in the soft deletion manager, no luck -
I can connect an application to 2 databases?
I have a web application in Python django. I need to import users and display data about them from another database, from another existing application. All I need is the user to be able to login and display information about them. What solutions are? -
How to display messages for api requests not admin in Django?
I want to have messages displayed on my admin page when a POST endpoint is used in my API. I am using the official messages framework from Django and have set them up accordingly: https://docs.djangoproject.com/en/4.0/ref/contrib/messages/ It does work for when I send requests on my Admin page (when I click a button for example). But it wont show when a POST function is runed. I see that the messages are saved somewhere but they are never showed. I tried both messages.warning(request, "message") and messages.add_message(request, constants.WARNING, "message") I assume its because I have a HTML template for admin. How can I join them, so that they display messages from both Admin and API? -
Why does timezone.now() + timezone.timedelta(days=1) at 12-1 AM return the same day?
Running timezone.now() + timezone.timedelta(days=1) at 12:30 AM returns datetime.datetime(2022, 2, 7, 23, 30, 00, 000000, tzinfo=<UTC>) which is practically still the same day. -
how to pass one function context variable to another function in django , or what is the good method instead of session for that?
views.py def contest(request): context = {} all_contest = Contest.objects.all() context["contest"] = all_contest return render(request,"contest.html",context) def contest_candidates(request,id): context = {} all_candidates_ = Contest_Candidates.objects.filter(contest_id = id) high_like = 0 winner_ = "" for i in all_candidates_: if i.likes_count > high_like: high_like = high_like + i.likes_count winner_ = i.owner.name context["cadidates"] = all_candidates_ return render(request,"view_contest_candidates.html",context) urls.py path("contest",views.contest, name="contest"), path("candidates/<id>",views.view_contest_candidates, name="candidates"), models.py class Contest(models.Model): title = models.CharField(max_length=50) class Contest_Candidates(models.Model): image = models.FileField( upload_to="contest_candidates/",) owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE) contest = models.ForeignKey(Contest, on_delete=models.CASCADE,related_name='candidates') @property def likes_count(self): return self.likes.all().count() class CandidateLikes(models.Model): like = models.CharField(max_length=10) user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='candidate_likes') contest_candidates = models.ForeignKey(Contest_Candidates, on_delete=models.CASCADE, related_name='likes') how to pass the winner variable in to contest function ? i need to show that in contest.html if it's not possible, which is the best method . want to show every contest winner in contest.html -
Navbar disappears after scrollIntoView() use on mobile view
Problem: NavBar disappears after scrollIntoView() used on mobile view. Related JS function scroll_to_chapters() { const chapters = document.getElementsByClassName("chapter_list")[0]; if (nav.classList.contains("nav-active")) { navLinks.forEach((link) => { if (link.style.animation) { link.style.animation = ''; } }); enableScroll(); burger.classList.toggle('toggle'); nav.classList.toggle('nav-active'); } chapters.scrollIntoView({ block: 'start', behavior: 'smooth' }) } I'm not quite sure but there might be a problem with the disabling and enabling scrolling. I didn't want mobile users to be able to scroll while the navbar menus are opened. Navbar HTML <div class="fix"> <header> <div class="container"> <nav> <a href="/" data-attr="img"><img src="{% static 'img/northernlogo.png' %}" class="logo" alt="logo"></a> <ul class="nav-links"> <li><a href="/">Home</a></li> <li><a href="/" onclick="scroll_to_chapters();return false;">Chapters</a></li> <li><a href="/about">About</a></li> <li><a href="/links">Links</a></li> </ul> <div class="burger"> <div class="line1"></div> <div class="line2"></div> <div class="line3"></div> </div> </nav> </div> </header> </div> Picture of the Error Before After How to Reciprocate Open the website on mobile view. Open the navbar from the home menu and click chapters. It'll take you to the chapters but now the navbar is gone. PS: Please hit me up if you need further info. -
How do I implement action={% url '......' %} in django-form
What would be the equivalent of using <form action={% url '......' %}> in django-form, if I don't want to directly use HTML form? -
Programmatically Assign an Existing Animated GIF Image from Static Directory to a Model Instance's ImageField
OK. Let's say I have this GIF located at: static/myproject/img/coming-soon.gif A Django model named "Note" with an ImageField. class Note(models.Model): featured_image = models.ImageField(upload_to=my_irrelevant_function, blank=True, max_length=155) My goal is to say: If the Note model's featured_image does not exist, I want to assign the "coming-soon.gif" file to the instance. Note: I can't set the default="some/path/to/my/coming-soon.gif for reasons I don't want to get into. Please just assume I can't. Here's the coming-soon.gif: It's 12 frames: >>> img.n_frames 12 Current code situation: from django.core.files.images import ImageFile from django.core.files.base import File, ContentFile from django.conf import settings from django.views.generic import CreateView from PIL import Image from io import BytesIO ... class NoteCreateView(CreateView): def create_featured_image_if_none(self): if (self.object.pk is not None) and (not self.object.featured_image): img = Image.open(settings.COMING_SOON_IMAGE) self.object.featured_image.save(f'{self.object.slug}.gif', content=File(open(settings.COMING_SOON_IMAGE, 'rb'))) self.object.save() This code produces a non-animated gif. I've seen examples like this: gif[0].save('temp_result.gif', save_all=True, append_images=gif[1:], loop=0) but I'm not clear on: Do I even NEED to loop through each frame to compile a list of frames to pass to append_images when I already have the actual GIF image I want to assign to my model's instance? How would I even loop through? I've seen seek(#) and tell() but wouldn't I just be recreating the entire GIF from … -
Open charge point protocol (OCPP) server implementation using Python Djago or Java Spring boot
I am programming a a PoC of OCPP server which can communicate with an EV charger using OCPP protocol, in Python Django and Java Spring boot. I was using a OCPP python package given in the link here and I was able to create a OCPP center system using Python and make connections. My server should be able to have the method to list all connected chargers, but I could not find any documentation about this. Is this method available on the Python OCPP package here. If not, can anyone tell me how to implement this method? Any help will be appreciated. -
Django api call function asynchronously
I have three servers. Server A: call server B when some event happened (send info to B) Server B (Django API Server): Use the info from A, call the api of server C. Server C (Machine API Server): Will create task following the info server B send to it. I'm working on server B, because we need an api server and data in the middle of server A and our machine(server C) The work my Django api server(server B) does is that async def check_status(token, taskUuid): def call(): res = requests.get(URL+"task/"+taskUuid, headers={ "accessToken": token }, verify=False) return res.json() while True: time.sleep(1) res_json = call() if res_json['status'] != 'RunningTask': print(res_json) # # do something that store info in the database # break @list_route(methods=['post']) def post_api(self, request): task_config = { 'info': request.data['info'] } if 'optionInfo' in request.data: task_config['optionInfo'] = request.data['optionInfo'] USERNAME="username" PASSWORD="password" URL="https://{machine_ip}/" login_res = requests.post(URL+"auth", json={ "username": USERNAME, "password": PASSWORD }, verify=False) login_json = login_res.json() token=login_json['AccessToken'] ## token task_res = requests.post(URL+"task", headers={ "contentType": "application/json", "accessToken": token }, json=task_config, verify=False) task_json = task_res.json() if task_json['status'] == 'RunningTask': taskUuid = task_json['uuid'] ## My question is here asyncio.run(check_status(token, taskUuid)) result = { task_created: 'success' } return Response(result, status=status.HTTP_200_OK) else: result = { task_created: 'failed' … -
dynamic user list consumer in Django channels
I'm using Django(3.2.11) with the Postgres database. I'm creating a chat app with Django channels. so I created a message consumer and save it into the database. and also created a message history consumer by room. now I want to create a user list consumer which has dynamic messages with the user name. for that I made a consumer who returns infinite data. like:- class ChatListConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_group_name = 'chat_list_%s' % self.scope['user'].user_id self.connection = True await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): self.connection = False await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) def get_serializer(self, obj): return {'data': ProductQueryUsersSerializer( instance=obj.order_by('-updated_at'), many=True ).data, 'type': "chat_list"} async def receive(self, text_data): while self.connection: try: self.query = await database_sync_to_async( ProductQueryUsers.objects.filter )(Q(seller__user=self.scope['user']) | Q(user=self.scope['user']) ) data = await database_sync_to_async(self.get_serializer)(self.query) except EmptyPage: data = {'data': [], 'type': "chat_list"} await self.send(text_data=json.dumps(data)) and call this in javascript like:- <div id="message"></div> <script> const chatSocket = new WebSocket('ws://192.168.29.72:8000/ws/chat-list/?user=VXNlcjo4Mg=='); chatSocket.onopen = function(e){ chatSocket.send(JSON.stringify({})); console.log("open", e); }; chatSocket.onmessage = function(e) { const data = JSON.parse(e.data); console.log(data) data.data.forEach(function (item, index, arr) { var element = document.getElementById(item.room_id); if (typeof(element) != 'undefined' && element != null){ document.getElementById(item.room_id).innerHTML = item.last_message.message } else { document.getElementById('message').innerHTML += `<h1 id="${item.room_id}">${item.last_message.message}</h1>` } }); }; chatSocket.onerror = function(e){ … -
How i convert my python code in multi-user mode. Multi-user mode means more than one person to work on my django web applcaton at the same time
how to Convert/change python Django web application from single to multi-user? How I convert my python code in multi-user mode. Multi-user mode means more than one person to work on my Django web application at the same time. I don't have any idea how I change my code to multi-user. In my web application user upload their file, in return, my python code generates 11 files for the user but if two users upload their files at the same time from different browsers the code s not execute properly and show an error. -
Find pk in queryset Django
I have a problem in obtaining a single id from a queryset. I post my models and views in order to be more clear: models.py class MissionEntry(models.Model): student = models.ForeignKey( Student, on_delete=models.DO_NOTHING, blank=True, null=True) mission = models.ForeignKey( Mission, on_delete=models.DO_NOTHING, null=True, blank=True) log_entry = models.ForeignKey( LogEntry, on_delete=models.DO_NOTHING, blank=True, null=True) learning_objective = models.ForeignKey( LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True) grade = models.CharField( max_length=10, choices=GRADING_VALUE, blank=True, null=True) note = models.TextField(blank=True, null=True) debriefing = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.mission) + ' ' + str(self.log_entry) class Meta: verbose_name_plural = 'Mission Entries' class MissionEntryStatus(models.Model): mission = models.ForeignKey( Mission, on_delete=models.PROTECT, null=True, blank=True) student = models.ForeignKey(Student, on_delete=models.PROTECT) is_completed = models.BooleanField(default=False) is_failed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class StudentMission(models.Model): mission = models.ForeignKey(Mission, on_delete=models.PROTECT) student_training_course = models.ForeignKey( StudentTrainingCourse, on_delete=models.PROTECT) mission_status = models.ForeignKey( MissionEntryStatus, on_delete=models.PROTECT, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['mission__name'] def __str__(self): return self.mission.name class LogEntry(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.DO_NOTHING) adep = models.ForeignKey( Aerodrome, on_delete=models.PROTECT, related_name='adep') ades = models.ForeignKey( Aerodrome, on_delete=models.PROTECT, related_name='ades') date = models.DateField() etd = models.TimeField() ata = models.TimeField() eet = models.TimeField() function_type = models.ForeignKey(FunctionType, on_delete=models.PROTECT) student = models.ForeignKey( Student, on_delete=models.PROTECT, blank=True, null=True) instructor = models.ForeignKey( Instructor, on_delete=models.PROTECT, blank=True, null=True) student_mission = models.ForeignKey( … -
OperationalError at /admin/app/question/ no such table: app_question (django)
Im new to this and Im tryna make a q&a type of app, I was just starting then when I went to admin/ to try it out I got OperationalError at /admin/app/question/ no such table: app_question Request Method: GET Request URL: http://127.0.0.1:8000/admin/app/question/ Django Version: 4.0.1 Python Version: 3.10.1 Installed Applications: ['app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'crispy_forms', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Exception Type: OperationalError at /admin/app/question/ Exception Value: no such table: app_question here is the models.py from django.db import models from django.contrib.auth.backends import ModelBackend from users.models import CustomUser # This is the question model class Question(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE) title = models.CharField(max_length=30) detail = models.TextField() add_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title # This is the answer model class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) detail = models.TextField() add_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.detail I'd appreciate if its explained in a beginner friendly manner, thank you! -
How do I pass primary key of the entry created by a django-form, to the next page after that
My Models.py contains 2 models, each Project can have multiple Role (i.e. one-to-many relationship): class Project(models.Model): title = models.CharField(max_length=2000) state_of_project = models.CharField(max_length=10, default='ongoing') introduction = models.TextField(blank=True) class Role(models.Model): role_name = models.CharField(max_length=30) project = models.ForeignKey(Project, on_delete=models.SET_NULL, null = True) def __str__(self): return self.role_name After submitting a form for model Project, I wanted to redirect user to fill the next form for model Role. The new roles added there should automatically have their foreign key project point towards the project created just before. How can I make that happen? I am specifically having problem adding mechanism of passing the primary key of model Project to the next form. -
How to statically add an image in django
Any one could help to add an image on the following view function, I tried adding the following way Category.objects.create( name='Others', slug='others', image='home/xxx/xx/static/assets/images/xxx.png' ) also tried Category.objects.create( name='Others', slug='others', image=static('home/xxx/xx/static/assets/images/xxx.png') ) image is not getting saved in both the ways -
The best way to optionally create accounts for the added employee
in my app the admin can add different employees and in my 'add employee' page i want to ask them if they want to also create a user account for them (so they will be able to login using a username and password). my employees has their own model, i want to know whats the best way to handle this in the models -
How to update 12k records in 1 minute in Django
I'm using Django(3.2.11) with the Postgres database. and we have 12k stocks symbols stored in a database. now we are updating their price in the database frequently with https://cloud.iexapis.com/stable/stock/{symbols}/intraday-prices?token={iex_api_key}&chartIEXOnly=true. now I required to update all 12k stocks price in 1 minute. for now im using celery periodic task. but I a task took more then 1 minute for completing. so how to update this all stocks in 1 minute -
How to access a value in a table connected by a Foreign Key
Currently I have a table called Load that has a relationship to a table called Container through a Foreign Key called Container_ID (the FK is just an integer). The foreign key lives in the Load table. Each row in the Load table has a Container_ID. The table Container has a column called Container_Name. What I want to do is to grab all rows from the Load table, and be able to tell what the actual container name is. Not the Container_ID, but the Container_Name that's in the Container table. I tried doing something like var = Load.objects.values_list('container_ID') but that only returns the actual foreign key integer, and I'm not sure how to take it that one step further to dive into the actual Container table to grab that Container_Name field.