Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to transfer/move products between inventory management tables using Django
Consider that I have a three database models, one for the backstore, another for the store(mainstore) and another for damaged products and i want to transfer product between these tables at the click of a button. My question is how can I move products that exist in one table to another. The operations should be simple addition and subtraction operation i.e., when I transfer product from the bacstore to the store, I want to deduct from the bacstore and add to the store and vice versa, same for damaged products I haven't tried anything yet too complex yet, overthinking about the logic mostly -
Autocomplete field in django inline admin overwrites filtered queryset
I have this inline admin: class AnalysedSampleInline(admin.TabularInline): formset = AnalysedSampleInlineForm model = SampleDataRelationship extra = 0 show_change_link = True autocomplete_fields = ("sample",) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "sample": kwargs["queryset"] = ( Sample.objects.select_related("person__family", "file") .order_by("person__family_id") .distinct() .filter(file__type=File.TYPE_BED) ) return super().formfield_for_foreignkey(db_field, request, **kwargs) The filter .filter(file__type=File.TYPE_BED) works fine without the autocomplete field but not with it. I found suggestions saying I should modify the "get_search_results" method. But this method does not exist for inline admins and is never called. How can I apply a filter to the autocomplete queryset of an inline admin? -
How to send an image to Django using Flutter web?
I'm working on a project that uses Flutter web as the client and Django as the backend server. I'm currently working on a registration form that requires to send an image + additional data. My problem is that it seems that there is an issue concerning the file upload, my view is working correctly in Django (I tested it many times) and wen i remove the file field from the django server, the request works perfectly, so I geuss the problem is in the file upload. final reader = html.FileReader(); reader.readAsArrayBuffer(logo); await reader.onLoad.first; final imageData = reader.result as List<int>; final request = http.MultipartRequest("POST", url); final multipartFile = http.MultipartFile.fromBytes('logo', imageData, filename: 'Any_name'); request.files.add(multipartFile); request.fields["nom"] = nom; request.fields["secteur_activite"] = secteurActivite; request.fields["description"] = description; request.fields["email"] = email; request.fields["first_name"] = firstname; request.fields["last_name"] = lastname; request.fields["phone"] = phone; request.fields["password"] = password; request.fields["password2"] = password2; final response = await request.send(); I've worked before with file uplaod between Django and Flutter and I always had problem using the .fromBytes method, the .fromPath method works fine but this method isn't available for Flutter web. Here is my Django code: class EntrepriseRegistrationView(GenericAPIView): serializer_class = EntrepriseSerializer parser_classes = (MultiPartParser,) def post(self, request): request.data serializer = self.serializer_class(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() data … -
Editing Django default two factor auth login page
So, is it possible to edit of the default Django two factor authentication login page ? I copied the files from my virtual environment to my project directory but it still uses the the default Django template. I have the correct paths and everything. How can I solve this issue I want to able to edit the Django two factor authentication login page to follow the rest of my web app, I want to get rid of the back and next buttons and have only a login button so when the user logs in, they can be taken to the token page(if they have 2 factor auth) -
Many-to-many relationship query in django
I have a many-to-many relationship like this in django, how do I make it so that I can execute the query "get all books written by the author Mattia" class Autore(models.Model): nome = models.CharField(max_length=100) def __str__(self): return self.nome class Libro(models.Model): titolo = models.CharField(max_length=100) autori = models.ManyToManyField(Autore, related_name="libri") def __str__(self): return self.titolo In views.py i try to do this but i can't get the right object. @api_view(["GET"]) def libri_autore(request, nome_autore): # Recupera l'autore dal database (si presuppone che il nome sia unico) autore = Autore.objects.get(nome=nome_autore) serializer = LibroAutoreSerializer(autore) print(autore) # Recupera tutti i libri associati a quell'autore libri = autore.libri.all() print(libri.values()) return HttpResponse("Libri recuperati con successo") -
Form is only submitted when there are two duplicate forms
I am trying to build a site using Django where users can submit coupon codes for their orders to get discounts. So I have a form in my cart.html file where user can enter Coupon Code and avail discount. But the bizarre thing is, the Apply Coupon function is only working when there are two duplicate forms on top of each other. If I remove even one of them and have a single form, as I should have, the code is not working, coupon is not applied, the page url gets stuck at http://127.0.0.1:8000/cart/?csrfmiddlewaretoken=ey3yy96SxX8msYViSD5aiT8TwCwyK5sCRJ9h48TMf3LQeGOmXFl05i2p7gLKta9s&coupon_code=SM20#. I have no idea why it only works when there are two forms and why it gets stuck when there is only one form. Can somebody help me out here please? Thanks in advance! My models.py: class CartItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='cart_items') course = models.ForeignKey(Course, on_delete=models.CASCADE) added_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user.username} added {self.course.title}" class Coupon(models.Model): code = models.CharField(max_length=20, unique=True) discount_percentage = models.PositiveIntegerField(null=True, blank=True) fixed_discount = models.PositiveIntegerField(null=True, blank=True) is_active = models.BooleanField(default=True) users_used = models.ManyToManyField(User, related_name='used_coupons', blank=True) def __str__(self): return self.code My views.py: @login_required def apply_coupon(request): if request.method == 'POST': coupon_code = request.POST.get('coupon_code') try: coupon = Coupon.objects.get(code__exact=coupon_code, is_active=True) if coupon.users_used.filter(id=request.user.id).exists(): messages.error(request, 'You have already used … -
Processing the a image when it got uploaded from admin site
I want to upload some transparent background png through the django admin site. But around the uploading I wish to processing them like making the background to be black. I have a class from models.py like this: class AllClass(models.Model): name = models.CharField(max_length=40, unique=True, help_text="Name of this class(e.g. Wardancer)") archetype = models.ForeignKey('Archetype', on_delete=models.RESTRICT, null=True) icon = models.ImageField(upload_to='icons',default='media/default/default_icon.jpg') A function like this should be called during or after the uploading: def recolor(url): image = Image.open(url).convert("RGBA") new_image = Image.new("RGBA", image.size, "BLACK") new_image.paste(image, mask=image) return new_image.convert("RGB") I tried this approach by adding it into my models.py file: @receiver(post_save, sender=Image) def crop_image(sender, instance, **kwargs): imgage = instance.image original = Image.open(imgage.src.path).convert("RGBA") new_image = Image.new("RGBA", original.size, "BLACK") new_image.paste(original, mask=original) instance.image = new_image It did not work maybe I did not do it the right way. To conclude, I want the image to be processed and preferably replaced with the processed image before the url got stored into the database -
Conditional filling of dropdown in Django backend with list_filters
My models.py: from smart_selects.db_fields import ChainedForeignKey class Funder(models.Model): name = models.CharField(max_length=200) scheme = models.ManyToManyField('Scheme', blank=True) class Scheme(models.Model): name = models.CharField(max_length=200) class Project(models.Model): funder = models.ForeignKey(Funder, on_delete=models.PROTECT) scheme = ChainedForeignKey( Scheme, chained_field="funder", chained_model_field="funder", show_all=False, auto_choose=True, sort=True, null=True, blank=True) As you can see I'm already using smart-selects for getting only the schemes that belong to that specific funder available in the Project dropdown selection in the admin back-end. smart-selects, though, doesn't take care of what happens in the list_filters section of the Admin. What I'd like to achieve: have two 'chained' dropdown filters in my Project admin table, where I'm filtering for projects that have a specific funder, and once I've filtered such projects I want to see only the schemes that belong to that specific funder in the schemes dropdown, with the ability of furter filtering the projects with that specific scheme. My failing attempt so far (admin/py): from admin_auto_filters.filters import AutocompleteFilter, class SchemeFilter( AutocompleteFilterFactory( 'new Scheme', 'scheme' ) ): def lookups(self, request, model_admin): funder = request.GET.get('funder__pk__exact', '') if funder: schemes= Scheme.objects.filter(funder__exact=funder).distinct() else: schemes = Scheme.objects.none() return schemes def queryset(self, request, queryset): funder = request.GET.get('funder__pk__exact', '') if funder and Scheme.objects.filter(funder__exact=funder).count(): return queryset.filter(scheme__exact=self.value()) return queryset class FunderFilter(AutocompleteFilter): title = 'Funder' field_name = … -
Is the server running on host "localhost" (127.0.0.1) and accepting web-1 TCP/IP connections on port 5432?
I have made a Django project with a postgresql backend and am trying to containerize it. This is my Dockerfile: Dockerfile This is my docker-compose.yml file: docker-compose.yml This is my settings.py within the django project to connect to the db: Settings.py The sudo docker build . command runs without any errors. The error I get when I try to run 'sudo docker compose up' is as follows: Is the server running on host "localhost" (127.0.0.1) and accepting web-1 TCP/IP connections on port 5432? I have confirmed that the postgres server is running: Server active(running) This application also runs without any errors on my local. I had created a network(inventory_network) on which I tried attaching my containers. But one thing I noticed was that whenever I ran the 'compose up' command, it created another network inventory_management_inventory_network automatically to which the containers attached instead of my specified network inventory_network: This is what I got when i ran 'inspect' on both these networks, as I wasn't sure if this was related to the issue: inventory_network inspect inventory_management_inventory_network inspect I have tried everything I know and would really appreciate any inputs. -
How to effectively use PUT and DELETE HTTP methods in Django Class-Based Views?
I'm setting up a CRUD system with Django, using Class-Based Views. Currently I'm trying to figure out how to handle HTTP PUT and DELETE requests in my application. Despite searching the Django documentation extensively, I'm having trouble finding concrete examples and clear explanations of how to submit these types of queries to a class-based view. I created a view class named CategoryView, extending from: django.views.View, in which I implemented the get and post methods successfully. And I want to build my urls like this: New Category: 127.0.0.1:8000/backendapp/categories/create List all Category: 127.0.0.1:8000/backendapp/categories/ Retrieve only one Category: 127.0.0.1:8000/backendapp/categories/1 Etc... However, when I try to implement the put and delete methods, I get stuck. For example : from django.views import View class CategoryView(View): template_name = 'backendapp/pages/category/categories.html' def get(self, request): categories = Category.objects.all() context = { 'categories': categories } return render(request, self.template_name, context) def post(self, request): return def delete(self, request, pk): return def put(self, request): return I read through the Django documentation and found that Class-Based Views support HTTP requests: ["get", "post", "put", "patch", "delete", "head ", "options", "trace"]. link: https://docs.djangoproject.com/en/5.0/ref/class-based-views/base/#django.views.generic.base.View Despite this, I can't figure out how to do it. So I'm asking for your help to unblock me. I looked at the … -
Django ORM, similar queries [duplicate]
Help me remove duplicates please, I’ve already tried everything, documentation, chatGPT, I don’t know how to remove it, it’s just that when I access the .html attribute a new request to the database is generated I'm using django-mailbox, I couldn't specify it because the rating is less than 1500. Models: https://django-mailbox.readthedocs.io/en/latest/_modules/django_mailbox/models.html messagesDB = Message.objects.filter(mailbox=mailbox).select_related('mailbox', 'message_used').prefetch_related(Prefetch('attachments', queryset=MessageAttachment.objects.all(), to_attr='all_attachments')) for message in messagesDB: print(message.html) SELECT ••• FROM "django_mailbox_messageattachment" WHERE "django_mailbox_messageattachment"."id" = 44 LIMIT 21 13 similar queries. **SELECT "django_mailbox_messageattachment"."id", "django_mailbox_messageattachment"."message_id", "django_mailbox_messageattachment"."headers", "django_mailbox_messageattachment"."document" FROM "django_mailbox_messageattachment" WHERE "django_mailbox_messageattachment"."id" = 44 LIMIT 21 13 similar queries.** C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\contrib\staticfiles\handlers.py in __call__(80) return self.application(environ, start_response) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\whitenoise\middleware.py in __call__(124) return self.get_response(request) C:\Users\user\AppData\Local\Programs\Python\Python310\lib\contextlib.py in inner(79) return func(*args, **kwds) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\views\generic\base.py in view(104) return self.dispatch(request, *args, **kwargs) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\contrib\auth\mixins.py in dispatch(73) return super().dispatch(request, *args, **kwargs) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\contrib\auth\mixins.py in dispatch(109) return super().dispatch(request, *args, **kwargs) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\views\generic\base.py in dispatch(143) return handler(request, *args, **kwargs) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\views\generic\base.py in get(226) context = self.get_context_data(**kwargs) C:\Users\user\Desktop\Задачник\ProjectsDashboard\dashboard\timetable\views.py in get_context_data(2109) messagesDB = self.get_message_telegram(self.mailbox) C:\Users\user\Desktop\Задачник\ProjectsDashboard\dashboard\timetable\views.py in get_message_telegram(2058) print(message.html) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in html(671) self.get_email_object(), 'text', 'html' C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in get_email_object(783) self._email_object = self._rehydrate(flat) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in _rehydrate(683) self._rehydrate(part) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in _rehydrate(683) self._rehydrate(part) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in _rehydrate(687) attachment = MessageAttachment.objects.get( C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\cacheops\query.py in get(327) return qs._no_monkey.get(qs, *args, **kwargs) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\cacheops\query.py in _fetch_all(250) return self._no_monkey._fetch_all(self) -
Can't understand how ForeignKey works
I'm designing a model for a company. It has several fields of activity: class Activity(models.Model): title = models.CharField(max_length=255) class Company(models.Model): title = models.CharField(max_length=255) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) And the admin: class ActivityInline(admin.TabularInline): model = Activity class CompanyAdmin(admin.ModelAdmin): inlines = [ActivityInline] But that gives me this error: company.Activity has no ForeignKey to company.Company And I know to fix it I have to do this: class Activity(models.Model): title = models.CharField(max_length=255) company = models.ForeignKey(Company, on_delete=models.CASCADE) class Company(models.Model): title = models.CharField(max_length=255) But the issue is, here the Company is the main model. One company has several activities not the other way around (OneToMany) so the ForeignKey should be defined in the Company model not the Activity. Or there's something I don't understand here? -
Must I create a model only within an app in Django, not in the project directly?
I created a project like so: $ cd dj-container $ django-admin startproject core . $ django-admin startapp app1 This means that core.apps does not exist, but app1.apps does. I want to create models under core, not app1 (some models that are nor app specific, but are project specific). I created a Country model under core, and on running makemigrations, I get this error: RuntimeError: Model class core.models.Country doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Do I have to add core in INSTALLED_APPS? And then perhaps creaate core.apps and create the app label. I am essentially making the core an app, and I vaguely think this is a wrong approach. Or do I just add an explicit app_label in the Model? Or should I create a separate app just for my common tables? -
Facebook Pixel popup not working on https but working when i am removing ssl its working fine
I have developed the website (http://littlestepwelfarefoundation.com/) on Django, taken domain from Godaddy, hosted on EC2 windows server and took ssl certificate from ACM only. When I am securing my site and routing http to https, facebook pixel is not firing, but when I am removing SSL and trying to access without https, it gets fired. -
Difference between regular def and lambda for reversing a url in django test
Consider the following two examples and explain to me why they are different (they look the same to me but the lambda does not work as expected) Using the lambda, I keep getting the following error: TypeError: SurveyConversationViewSetTestCase.setUpTestData.<locals>.<lambda>() missing 1 required positional argument: 'pk' nested url /api/surveys/<survey_pk>/survey-conversations/<pk>/ survey_conversations.views.SurveyConversationViewSet survey-conversations-detail Test class SurveyConversationViewSetTestCase(UserSetupMixin, APITestCase): @classmethod def setUpTestData(cls): super().setUpTestData() cls.update_url = lambda self, pk: reverse( "survey-conversations-detail", kwargs={"survey_pk": cls.survey.pk, "pk": pk} ) def get_update_url(self, pk): return reverse( "survey-conversations-detail", kwargs={"survey_pk": self.survey.pk, "pk": pk}, ) # this fails def test_with_lambda(self): response_create = self.client.post( self.create_url, {"participant_id": self.participant.pk} ) conversation_id = response_create.data["conversation_id"] self.client.patch(self.update_url(str(conversation_id)),{"answer": "Walking"}) # this passes def test_with_def(self): response_create = self.client.post( self.create_url, {"participant_id": self.participant.pk} ) conversation_id = response_create.data["conversation_id"] update_url = self.get_update_url(conversation_id) response = self.client.patch(update_url, {"answer": "Walking"}, format="json") -
I try to ,make a fixture in Django, using dumpdata, and instead of letters i have symbols
when i try do to a fixture in Django, i use dumpdata, and when I create a JSON file, where the name is, instead of letters there are some symbols, I use this command python manage.py dumpdata goods.Categories > fixtures\goods\cats.json my json file after, is looking like this { "model": "goods.categories", "pk": 4, "fields": { "name": "┬ёх ЄютрЁ√", "slug": "all" } -
Can't access sessionid and csrftoken on Chrome
I am struggling. Right now I am trying to figure out this block. Maybe i havent looked hard enough but I have been at this for a whole entire day. Figured this would be my last resort. Right now I am trying to send the sessionid cookie (from DRF) back to Django (from React) in order to keep track of some data. The user does not have to be authenticated for this to work. When a user makes a request and there is no session key, I populate a new session with some data and return a response to the user. FROM MY UNDERSTANDING, the sessionid cookie is sent along with the response from DRF which is stored in the browser cookers. That way, subsequent requests send those cookies (using "credentials: include") back to Django so that we can keep track of a session. Great. The problem is that: when I create a new session and make another request, it creates a new session instead of accessing the one that was initially made. This is because the session_key is None when I try to access it in the request on the backend which leads the view to create a new … -
Is there a good way to manage very long translation texts in Django?
For Django i18n, it is common to use makemassages and compilemessages to create django.po and django.mo files. It works very well for translating short text fragments, and in fact I've been able to i18n almost all of my website using it. Usually, however, a website is not just fragmented text, but has several pages containing very very long sentences, such as "Terms of Use," "User Guide," and so on. If we try to translate them using Django's features (trans, blocktrans), the po file become hard to manage. It seems silly to me to manage these fragmented texts and very long sentences in one po file. So I have a question. Is there any way to split up the po files? It would be a solution if I could create a po file specifically for pages containing such long sentences, but I couldn't find such an option in the Django manual. Or is there another better way? I'd like to avoid having separate template files for each language and using {% if %} on the templates to display them. (but unfortunately, that's actually how I'm dealing with it now) I checked the Django manual; I also checked the gettext manual. But … -
Is it possible to pass two variables in a Django redirect?
I am trying to create dynamic URLS in Django with two variables like the ones below: path('fin-data-add/<str:fintype>/fin-data-update/<str:pk>', views.finDataUpdate, name='fin- data-update'), path('fin-data-add/\<str:fintype\>/fin-data-delete/\<str:pk\>', views.finDataDelete, name='fin-data-delete') path('fin-data-add/\<str:fintype\>/fin-categories/fin-categories-delete/\<str:pk\>', views.finCatDelete, name='fin-categories-delete') And I am trying to pass these variables in my views.py in the way below: @login_required(login_url='home:login') def finDataUpdate(request, fintype, pk): expense = Expenses.objects.get(id=pk) form = ExpenseForm(instance=expense) if request.method == 'POST': form = ExpenseForm(request.POST, instance=expense) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() return redirect('boost:fin-data-update', kwargs={'fintype': fintype, 'pk': pk}) database = Expenses.objects.all() fin_type = 'Expense' fin_type_plural = 'Expenses' context = {'form': form, 'database': database, 'fin_type': fin_type, 'fin_type_plural': fin_type_plural} return render(request, 'boost/fin-data-update.html', context) But I am getting the error below: NoReverseMatch at /boost/fin-data-add/expense Reverse for 'fin-data-update' with arguments '(45,)' not found. 1 pattern(s) tried: ['boost/fin\\-data\\-add/(?P<fintype>[^/]+)/fin\\-data\\-update/(?P<pk>[^/]+)\\Z'] Is it possible to pass two variables like I am trying? -
How can I implement a basic program-wide translation function into my Django project?
I'm making something for my Computer Science coursework which is a POS system running on Django. Here's my repo: https://github.com/Ashaz/django_point_of_sale Background Info So basically, the program itself isn't reviewed by the examiners. However, I need to evidence that the features I have are working by recording a short video of my program in use. It doesn't matter if the actual features don't perform the FULL intended purpose. For example, in this program it says "Sales" but because I'm catering mine towards the catering industry, ideally it would say "Orders". I've been allowed to use a fork of the original project. My Problem So, the main goal of my project is to make it so that the user can select a language to translate into and the program then translates the page into that language. The thing is I can just include the Google translate form on the page but I need to go a step further to evidence I've actually done some work, meaning I need to use APIs or something. The translation does not need to be 100% accurate but rather show an attempt was made; there's limitations like being a student and studying subjects which allow justification. I … -
Python opentelemetry wsgi usage with gunicorn / Application Insights
I have the below setup working perfectly in development mode in my django application, so when I run python manage.py runsslserver the application reports perfectly to Application Insights. from azure.monitor.opentelemetry import configure_azure_monitor from django.conf import settings as my_settings def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my.settings') # Configure OpenTelemetry to use Azure Monitor with the specified connection string AZ_OPENTELEMETRY_CONNECTION_STRING = impact3_settings.AZ_OPENTELEMETRY_CONNECTION_STRING configure_azure_monitor( connection_string=AZ_OPENTELEMETRY_CONNECTION_STRING, ) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() However, when I move this into production, we're utilizing gunicorn and wsgi, so, manage.py isn't ever running. I've found a way to to add OpenTelemetryMiddleware to the wsgi file, but have no idea how/where to call the configure_azure_monitor to record every request. What am I missing? import os from django.core.wsgi import get_wsgi_application from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my.settings') application = get_wsgi_application() application = OpenTelemetryMiddleware(application) -
Django Model Permissions. Why is this hard?
Django creates permissions for every model you make, such as: can_view_{model_name} can_add_{model_name} can_edit_{model_name} Out of the box, these are only applicable to Django Admin. Ok well if I want to apply them at the model level, why can't I do: class MyModel(models.Model) def can_view(self, user): if user.has_perm('my_app.can_view_my_model'): return True return False And then any time the ORM tries to lookup that model, it has to check the permission first. Instead, I have to go into each View and manually check: class MyModelDetail(APIView): @transaction.atomic def get(self, request): try: if not request.user.has_perm("my_app.can_view_my_model"): raise APIException("You do not have permission to view this model") And repeat that across all views that look up my model. Is there an easier way? -
How to generate file in MEDIA_ROOT in Django?
In my view I have a function that generates a file but does not return anything. I want the file to be generated in a specific folder in MEDIA_ROOT and saved in my models but I'm not sure how exactly to go about doing it. Here is the relevant section of my view: writer = get_writer(output_format, output_dir) This function generates a file in the stated directory. I want to save it to a specific directory relevant to my MEDIA_ROOT. Here is the relevant section of my settings.py file: MEDIA_URL='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') The destination directory, for example, can be media/destination_directory but I'm not sure how to write the path relative to MEDIA_ROOT -
RuntimeError('Event loop is closed') in Django Rest Framework with google generative ai
I am using google generative ai in django rest framework. I send a request in my backend with adrf (async views package), I can process my answer with Gemini pro, but when I send other request I get this error: raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed [11/Apr/2024 15:20:49] "POST /api/chatbot/ HTTP/1.1" 500 165320 C:\Users\User\Documents\Python\chatbot-django-entrevista\apps\chatbot\views\gemini_views.py changed, reloading. sys:1: RuntimeWarning: coroutine 'UnaryUnaryCall._invoke' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback Watching for file changes with StatReloader Performing system checks... This is my code: import google.generativeai as genai genai.configure(api_key=settings.GOOGLE_API_KEY) @async_api_view(['POST']) async def post_message(request): """ This view post a message """ model = genai.GenerativeModel(settings.MODEL) messages = [ {'role':'user', 'parts': ["Briefly explain how a computer works to a young child."]} ] response = await model.generate_content_async(messages) print(response) return Response({'msg':'text'}) -
Why I can't start Django web site with docker?
I have a Django web app and I need to launch it with docker. I created two images: one for Django and another for postgresql. It successfully builds but during the composing up shows the problem that django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 or psycopg module. Seems like docker didn't install psycopg2 from requirements.txt. Dockerfile: # Here I'm creating an image for Django. FROM python:3.10.0-alpine COPY requirements.txt /requirements.txt COPY movies_admin /movies_admin WORKDIR /movies_admin EXPOSE 8000 RUN apk add postgresql-client build-base postgresql-dev RUN pip install -r requirements.txt docker-compose.yml services: django: build: context: . ports: - "8000:8000" volumes: - "./movies_admin:/movies_admin" environment: - DB_HOST=database - POSTGRES_DB=movies_database - POSTGRES_USER=app - POSTGRES_PASSWORD=123qwe command: sh -c "python3 manage.py runserver 0.0.0.0:8000" depends_on: - database database: image: postgres:16 environment: - POSTGRES_DB=movies_database - POSTGRES_USER=app - POSTGRES_PASSWORD=123qwe requirements.txt asgiref==3.8.1 autopep8==2.1.0 black==24.3.0 click==8.1.7 Django==5.0.4 django-split-settings==1.3.1 flake8==7.0.0 mccabe==0.7.0 mypy-extensions==1.0.0 packaging==24.0 pathspec==0.12.1 platformdirs==4.2.0 psycopg2==2.9.9 psycopg2-binary==2.9.9 pycodestyle==2.11.1 pyflakes==3.2.0 python-dotenv==1.0.1 sqlparse==0.4.4 tomli==2.0.1 typing_extensions==4.11.0