Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does my Django view return 'Reverse for 'initiate_transcription' with arguments '('',)' not found'?
A user uploads a file on page 1 and the site redirects them to page 2 where they can click a button which triggers the service. I'm trying to create a unique URL for each user upload and I know the error has to do with the {% url 'initiate_transcription' session_id %} in HTML page 2 form but i'm not sure what to change. Here is the code: urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.transcribeSubmit, name = "transcribeSubmit"), path("init-transcription/<str:session_id>/", views.initiate_transcription, name = "initiate_transcription"), ] views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) request.session['uploaded_file_name'] = filename request.session['uploaded_file_path'] = fs.path(filename) session_id = str(uuid.uuid4()) request.session['session_id'] = session_id # Render the 'transcribe-complete.html' template to a string return JsonResponse({'redirect': reverse('initiate_transcription', args=[session_id])}) else: else: form = UploadFileForm() @csrf_protect def initiate_transcription(request, session_id): if request.method == 'POST': try: # get the file's name and path from the session file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') if file_name and file_path: with open(file_path, 'rb') as f: path_string = f.name transcript = transcribe_file(path_string,audio_language, output_file_type ) file_extension = ('.' + (str(file_name).split('.')[-1])) transcript_name = file_name.replace(file_extension, … -
Django inline with PolymorphicParentModelAdmin
i have a problem with my CreationInline, i have this code in models.py: class Creation(PolymorphicModel): """Model representing a creation.""" original_title = models.CharField('Título original', max_length=10000, null=True, blank=True,) subtitles = models.TextField('Subtítulos, capítulos y entregas', null=True, blank=True,) authorship = models.TextField('Autoría', null=True, blank=True,) publication_year = models.IntegerField("Año de publicación",default=2023, choices=((i,i) for i in range(1930, 2024))) synopsis = models.TextField('Sinopsis', null=True, blank=True,) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True,) keywords = models.ManyToManyField(KeyWord, blank=True) product = models.OneToOneField("Product", on_delete=models.CASCADE, related_name="product_creation") def __str__(self): return self.product.title class MediaCreation(Creation): original_language = models.ForeignKey(Language, on_delete=models.SET_NULL,blank=True, null=True) IMDb = models.CharField(max_length=10000,blank=True, null=True) commertial_editions = models.CharField('Ediciones comerciales', max_length=10000,blank=True, null=True) class Movie(MediaCreation): """Model representing a Movie.""" remastering = models.TextField('Reedición', null=True, blank=True) direction = models.TextField('Dirección', null=True, blank=True) producer = models.TextField('Producción', null=True, blank=True) genre = models.ManyToManyField(Genre, limit_choices_to={"type": "Movie"}) there are other models that inherit from Creation, such us Novel, Comin, etc. My code in admin.py is: class CreationInline(NestedStackedInline): model=Creation class CreationParentAdmin(PolymorphicParentModelAdmin): """Parent admin class for Creation model.""" base_model = Creation child_models = (Movie, Musica, TVSerie, Videogame, Theatre) @admin.register(Creation) class CreationAdmin(CreationParentAdmin, DisableAddButtonModelAdmin): """Admin class for Creation model.""" base_model = Creation readonly_fields = ('product',) child_models = (Movie, Musica, TVSerie, Videogame, Theatre, Novel, Comic, BoardGame) list_filter = (PolymorphicChildModelFilter, ) list_display = ('get_product_title', 'original_title', 'authorship', 'publication_year') def get_product_title(self, obj): return obj.product.title # Obtiene el título … -
Printing to thermal printer in python
I have been trying to print on a POS printer and a label printer, depending on the running function. Here is where I am at: import win32print, win32ui, win32con # X from the left margin, Y from top margin # both in pixels X=50; Y=50 # Separate lines from Your string # for example:input_string and create # new string for example: multi_line_string # @@@@@@@ lable = Lable.objects.all().last() # @@@@@@@ multi_line_string = label_text.splitlines() the_name_will_appear_on_printer_spool = str(f"print_job{lable.id}") hDC = win32ui.CreateDC () # Set default printer from Windows: # hDC.CreatePrinterDC (win32print.GetDefaultPrinter ()) hDC.CreatePrinterDC(win32print.OpenPrinter(printers.label)) hDC.StartDoc (the_name_will_appear_on_printer_spool) hDC.StartPage () for line in multi_line_string: hDC.TextOut(X,Y,line) Y += 50 print(hDC.TextOut.text()) hDC.EndPage () hDC.EndDoc () message.success(request, 'Test printer job send') I have been using p = win32print.OpenPrinter("EPSON LX-350") to grab a specific printer but in this case i need to use something like this: hDC.CreatePrinterDC (win32print.OpenPrinter("EPSON LX-350")). The problem is I'm getting this error: Objects of type 'PyHANDLE' can not be converted to Unicode. Since i grabbed this from a 2013 answer there may be a better way to do this, I'm open to suggestions. Thank you in advance -
DJango Left join issues
LEFT JOIN ISSUE Model1 KPI_ID KPI_Name 1 KPI1 2 KPI2 3 KPI3 4 KPI4 Model2 Emp_Name KPI_ID Amount Mr. A 1 100 Mr. A 3 200 Mr. B 2 300 Mr. B 4 400 Output For Employe : Mr. A KPI_ID KPI_Name Amount 1 KPI1 100 2 KPI2 NULL 3 KPI3 200 4 KPI4 NULL For Employe : Mr. B KPI_ID KPI_Name Amount 1 KPI1 NULL 2 KPI2 300 3 KPI3 NULL 4 KPI4 400 Django left join issue -
best practice for dynamic filtering
I want to filter with keywords the user can enter. for example: models.py: class Product(models.Model): name = models.CharField(max_length=128) description = models.CharField(max_length=256) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() now I want to let the user enter "category": "teapot" or "name": "IKEA Glas 0.5L" and the code should in the get_queryset method execute: def get_queryset(self): VALUE = self.request.GET.keys(SOMEPARAM) return Product.objects.filter(SOMEPARAM__contains=VALUE) how can this be done (I know I can do a lot of if clauses, but my model is quite large in terms of fields that can all be handled equally. so for example for the IKEA example that would be: Product.objects.filter(name__contains="IKEA Glas ...") -
Getting CORS error after adding Dockerfile to my Django project
So to keep it brief, I have a fullstack application which is deployed on Railway. Everything worked perfectly. Then I decided to integrate celery so I can run some tasks in background. Now in order to use celery in production I wanted to containerize my Django app where it can also run celery. So I followed some tutorials and added Dockerfile to my Django app. Dockerfile: FROM python:3.9.7 WORKDIR /app COPY . /app RUN pip install -r requirements.txt ENV DJANGO_SETTINGS_MODULE=backend.settings ENV CELERY_BROKER_URL=redis://default:***********************-43.railway.app:**** ARG RAILWAY_ENVIRONMENT ENV PORT = 8080 EXPOSE 8080 CMD ["python", "-m", "celery", "-A", "backend", "worker", "--loglevel=info","--pool=solo"] Everysince I added this, my application is facing this CORS issue..I dont know why and I searched thru google and I couldnt find any answers, I am new to Docker so I hope to get some insight on this. Here is my CORS config in Django: CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'https://checkout.stripe.com', 'https://sendit-frontend-production.up.railway.app' ] CORS_ALLOW_CREDENTIALS = True MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] -
How to get a prefilled authorization key in swagger with drf-specatular
I use django, drf and drf-spectacular. I create swagger documentation. Some endpoints require authentication. I can authenticate in swagger by pressing authorize and filling in the token. I would like that this filled in automatically for me. How do I do that? I tried to add preauthorizeApiKey to my settings, like this: SPECTACULAR_SETTINGS = { 'SWAGGER_UI_SETTINGS': { 'preauthorizeApiKey': 'Token my-secret-token' } } It doesnt work. -
after implementing serial number the sorting of serial number is not working.answer will be appreciated
after implementing serial number the sorting of serial number is not working.answer will be appreciated. i did serial number of jquery datatable.i used django and jquery datatable and after implementing serial number the sorting of serial number is not working.answer will be appreciated. -
Why do get requests to amazon.nl work but not to amazon.com / amazon.de?
Currently I am trying to build an amazon web scraper which scrapes some information of an item from the product page. For this I am using LXML and parsing the data using xpath. The main problem I am facing is that when I make a get request to amazon.nl only about 1/10 of them are successfull, but when I try to make one to amazon.de, or amazon.com, it takes a very long time for it to return an answer(if it ever does). HEADERS = ({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/117.0.0.0 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5'}) while True: response = requests.get(URL, HEADERS) if response.status_code != 503: break currently this is all the code I am using to make the get requests. Can someone help on how this could be improved (better success ratio) or explain why I cant seem to make get requests to amazon.de / amazon.com also as I side not I am living in the netherlands which could play a part on why I can access amazon.nl -
Django logging filter used at startup, but not during HTTP events
I have a Django project which produces a lot of useless log messages when static entities are fetched via HTTP GET. I tried this in settings.py LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { # <-- I added this 'skip_static_media': { '()': 'django.utils.log.CallbackFilter', 'callback': do_skip_static_media } }, "handlers": { "console": { "class": "logging.StreamHandler", "filters": ['skip_static_media'], # <--- I added this }, }, "root": { "handlers": ["console"], "level": "WARNING", }, } with def do_skip_static_media (record): # This is for debugging only import sys sys.stderr.write (">>>do_skip_static_media:" +repr(record)) msg = record.args[0] if msg.startswith ("GET /debughistory_sidebar/") \ or msg.startswith ("GET /static/"): return False return True What happens is that the log shows this during startup Watching for file changes with StatReloader >>>do_skip_static_media:<LogRecord: django.utils.autoreload, 20, /django-template-venv/lib/python3.10/site-packages/django/utils/autoreload.py, 668, "Watching for file changes with %s">Watching for file changes with StatReloader Performing system checks... but do_skip_static_media is not used during any HTTP requests. How do I catch every HTTP event and filter those? -
Error message "WebSocket HANDSHAKING - WebSocket REJECT - WebSocket DISCONNECT" in Django Channels
I recently followed the official Django Channels documentation (version 4.0.0) to set up WebSockets in my Django project. I've gone through the documentation tutorial and configured my project correctly. However, when I attempt to test the service using websocketking, I'm encountering a handshaking issue. Here are some details about my configuration: My asgi.py file looks like this: import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "schatai.settings") django_asgi_app = get_asgi_application() import schatai.routing application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(schatai.routing.websocket_urlpatterns)) ), } ) My consumers.py file looks like this: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class WsTestConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "chat_message", "message": message} ) # Receive message from room group def chat_message(self, event): message = event["message"] # Send message to WebSocket self.send(text_data=json.dumps({"message": message})) My routing.py file looks like this: from django.urls import re_path, path from . import consumers websocket_urlpatterns = [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.SchataiConsumer.as_asgi()), path(r"ws/", consumers.WsTestConsumer.as_asgi()), ] I've also configured my settings.py file in accordance with the documentation. … -
I am creating an inventory mgt app, however when i try to return_item using_item Used i get an error # ValueError at /return_item/
I am creating an inventory mgt app, however when i try to return_item using_item Used i get an error # ValueError at /return_item/ when i try to return an item say x was give 5 bags of cement but ended up using 2.5 x returns the 2.5 items remainining but when i try to do this gives me an error AS stated above Django Model Definitions: IssueItem: class IssueItem(models.Model): id = models.BigAutoField(primary_key=true) person = models.ForeignKey(Person, on_delete=models.CASCADE) grouped_item = models.ForeignKey(GroupedItems, on_delete=models.CASCADE, related_name='issue_items') units_issued = models.DecimalField(max_digits=7, decimal_places=2, default=0) Date = models.DateField(default=timezone.now) def save(self, *args, **kwargs): self.grouped_item.calculate_totals() super().save(*args, **kwargs) return_item: python Copy code class return_item(models.Model): id = models.BigAutoField(primary_key=true) person = models.ForeignKey(Person, on_delete=models.CASCADE) grouped_item = models.ForeignKey(GroupedItems, on_delete=models.CASCADE, related_name='returned_items') units_returned = models.DecimalField(max_digits=7, decimal_places=2, default=0) Date = models.DateField(default=timezone.now) def save(self, *args, **kwargs): self.grouped_item.calculate_total() super().save(*args, **kwargs) def __str__(self): return self.Person GroupedItems: python Copy code class GroupedItems(models.Model): id = models.BigAutoField(primary_key=true) grouped_item = models.CharField(max_length=30, unique=true) total_units = models.DecimalField(max_digits=9, decimal_places=2, default=0) total = models.PositiveIntegerField(default=0) units_used = models.DecimalField(max_digits=8, decimal_places=2, default=0) units_available = models.DecimalField(max_digits=8, decimal_places=2, default=0) Units_returned = models.DecimalField(max_digits=8, decimal_places=2, default=0) def calculate_total(self): return_items = self.returned_items.all() self.Units_returned = return_items.aggregate(units_returned=Sum('units_returned'))['units_returned'] or 0 self.units_used = self.units_used - self.Units_returned def calculate_totals(self): issue_items = self.issue_items.all() self.units_used = issue_items.aggregate(units_issued=Sum('units_issued')['units_issued'] or 0 self.units_used = self.units_used - self.Units_returned self.units_available … -
Cannot Email By GoDaddy Office365 in Django ([Errno 101] Network is unreachable)
I have deployed my Django project on GoDaddy hosting. I have a problem while emailing by SMTP server using the provided Office365 mail on GoDaddy. The config which I set for emailing is code below. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST_USER = 'no-reply@domain.com' EMAIL_HOST_PASSWORD = 'password' But while sending an email by the send function from an instance of Django EmailMessage class, error “[Errno 101] Network is unreachable” is being returned (I have also tried different ports none of them has solved the problem yet). I thank anyone to guide me with the solution. Thanks, -
How to make Model QuerySet from a Django model instance
I have a model instance in Model's clean() method, and I want to add it to a QuerySet like below. def clean(self) -> None: #here self == model instance I need to add to queryset if self.id: from django import forms g=dag.DAG() g.create(self) if not g.validate_DAG(): self.custom_exception="Check hierarchy of users, cyclic dependency being created" raise forms.ValidationError(f"{self.custom_exception}") return super().clean() def create(self, update_cashback_relation): try: # Create a directed graph from catalog.models import UserRelationCashback self.G = nx.DiGraph() # # Add nodes to the graph user_relations_data=UserRelationCashback.objects.all() user_relations_data.get(id=update_cashback_relation.id).delete() user_relation_updated=user_relations_data.get(id=update_cashback_relation.id) print(user_relations_data.get(id=update_cashback_relation.id).__dict__) user_relations_data = user_relations_data | update_cashback_relation #this won't work as we must have both queryset, but i have a model instance and a queryset user_relations=user_relations_data.values("user", "manager", "product_group_category_warranty") users=user_relations.distinct().values_list("user", flat=True) # Add nodes to the graph for user in users: self.G.add_node(user) # Add directed edges to the graph for user_relation in user_relations: self.G.add_edge(user_relation.get('user'), user_relation.get('manager')) # Visualize the directed graph pos = nx.spring_layout(self.G) matplotlib.use('Agg') fig, ax = plt.subplots() # Draw the directed graph with arrows nx.draw(self.G, pos, with_labels=True, node_size=500, node_color='skyblue', font_size=10, font_color='black', arrows=True, ax=ax) # Save the graph as an image plt.savefig('directed_graph.png', format='png') plt.show() except Exception as e: raise Exception(f"{e}") -
why i use enctype='application/json' but CONTENT_TYPE still be application/x-www-form-urlencoded
<form enctype='application/json' action="{% url 'xxx' %}" method="post"> {% csrf_token %} <input type='number' name='bottle-on-wall' value='1'> <input type='number' name='bottle-on-wall' value='2'> <input type='number' name='bottle-on-wall' value='3'> <button type="submit">send</button> </form> CONTENT_TYPE 'application/x-www-form-urlencoded' how can i send the form data as json to server -
How can I process, stream a video and render the results in Django?
I'm currently involved in a real-time machine learning project that seamlessly integrates with Django. In this endeavor, I'm deeply immersed in processing and live-streaming video content. This multifaceted process encompasses the capture of video frames, their real-time processing, and their seamless streaming to a web application. Furthermore, I've integrated the Firebase Realtime Database to facilitate the storage and retrieval of data associated with the video stream. Here's a brief overview of what the code does: Here, I have a generator function called 'generate(camera),' which captures frames and yields them as a multipart stream. Within the 'generate' function, I simultaneously process video frames, detect actions, and yield each frame with a content type of 'image/jpeg.' Upon the completion of video processing, indicated by an end marker, the processed data is stored in a database, and the user is redirected to a results page. def generate(camera): action_labels = ['field_goal', 'pass', 'run', 'touchdown'] actions = {'actions': {}} while True: data = camera.get_frame() if len(data) == 4: frame = data['frame'] results = data['results'] action = data['action_bboxes'] timestamp = data['timestamp'] if len(action) > 0: try: action_result = action_labels[action[0][0]] actions['actions'][timestamp] = action_result # actions.append(action_data) except: pass if frame: yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n' else: … -
Django-import-export library - No such file or directory: '/tmp/tmp5bcxsx9p'
I have a problem with the django-import-export library because when I try to import excel or csv files it gives me error 500, and the error returned is the following FileNotFoundError [Errno 2] No such file or directory: '/tmp/tmp5bcxsx9p' and the error comes from django-import-export library in the file import_export/tmp_storages.py in _open() def _open(self, mode="r"): if self.name: return open(self.get_full_path(), mode, encoding=self.encoding) <---- else: tmp_file = tempfile.NamedTemporaryFile(delete=False) self.name = tmp_file.name return tmp_file this is the code in the Django admin of the model that im trying to import info class ProductForeignKeyWidget(ForeignKeyWidget): def get_queryset(self, value, row, *args, **kwargs): qs = super().get_queryset(value, row, *args, **kwargs) return qs.filter(shop__tpc_shop=int(row['ID TIENDA']), sku=row['SKU'].upper().strip()) class StockResource(resources.ModelResource): shop = Field( column_name='ID TIENDA', attribute='shop', widget=ForeignKeyWidget(Shop, 'tpc_shop') ) product = Field( column_name='SKU', attribute='product', widget=ProductForeignKeyWidget(Product, 'sku') ) units = Field( column_name='UNIDADES', attribute='units', widget=IntegerWidget(), default=0, ) threshold_units = Field( column_name='UMBRAL', attribute='threshold_units', widget=IntegerWidget(), default=10, ) location = Field( column_name='LOCALIZACION', attribute='location', widget=OurCharWidget(), default='No location', ) @classmethod def get_error_result_class(self): """ Returns the class used to store an error resulting from an import. """ return SimpleError class Meta: model = Stock use_transactions = True skip_unchanged = True report_skipped = True import_id_fields = ('product',) fields = ('id', 'units', 'threshold_units', 'location') def before_import_row(self, row, row_number=None, **kwargs): row['SKU'] = str(row['SKU']).strip() … -
To know the number of objects being serialized at that time. DRF
I have a serializer which will serialize an object. Is there a way to know if it's serializing one object or multiple objects at that time? I have a serializer and I have a custom method field in that. I need to call one API if it's a single objects it is serializing or if it's serializing multiple objects, I need to call a different API. -
Django/pytest: Requested setting REST_FRAMEWORK, but settings are not configured
I'm working on a Django project and using pytest for testing. I have written a very simple test case - class TestwordOfTheDay(TestCase): def setUp(self): print("Test passed") def test_json_response(self): json_response = { "id": 43, "wordOfTheDayinHindi": "अस्पष्ट", "wordOfTheDayinEnglish": "ambiguous", "wordOfTheDayinEnglish_Usage_Example": "Everyone listened to the weather report, but the forecast was ambiguous and no one knew if it was going to be rainy or sunny today.", "wordOfTheDayinHindi_Usage_Example": "हर किसी ने मौसम के समाचार को सुना था, लेकिन उनका पूर्वानुमान अस्पष्ट था और कोई भी यह नहीं जान पाया कि आज बरसात होगी या धूप खिलेगी।", "date": "2023-10-19" } response = JsonResponse(json_response) self.assertTrue(isinstance(json_response["id"], int)) self.assertRegex(json_response["wordOfTheDayinHindi"], r"[ऀ-ॿ]+$") self.assertRegex(json_response["wordOfTheDayinEnglish"], r"^[a-zA-Z]+$") self.assertRegex(json_response["wordOfTheDayinEnglish_Usage_Example"], r"^.*\b" + re.escape(json_response["wordOfTheDayinEnglish"]) + r"\b.*[.?!]$") self.assertRegex(json_response["wordOfTheDayinHindi_Usage_Example"], r"^.*\b" + re.escape(json_response["wordOfTheDayinHindi"]) + r"\b.*[.?!]$") self.assertEqual(json_response["date"], str(date.today())) However, when I run pytest, I encounter the following error: django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I'm not sure how to resolve this issue. Any help or guidance on how to fix this error would be greatly appreciated. -
Django Programming Error: Cannot Cast Type bigint to uuid
I'm facing an issue while trying to change the data type of a column in my Django model from bigint to uuid in a PostgreSQL database. The error message I'm encountering is: django.db.utils.ProgrammingError: cannot cast type bigint to uuid LINE 1: ...me_studentrest" ALTER COLUMN "id" TYPE uuid USING "id"::uuid -
Mocking instance methods in python unittest
I'm a software developer for several years but new to python. I'm writing a unit test (so no database connection present) that involves a model in Django that accesses another model referenced via a foreign key connection. I want to mock the method that accesses this connection and replace the result with a hard coded response, that is different for each instance though. Here's a minimal example: ### tests/test_MyTestCase.py from unittest import TestCase from djangoapi.models import * class MyTestCase(TestCase): def setUp(self): self.instance1 = MyModel() self.instance2 = MyModel() foreignKey1 = MySubModel() foreignKey1.my_value = 1 # Mock that self.instance1.submodel_set.all() returns [foreignKey1] foreignKey2 = MySubModel() foreignKey2.my_value = 2 # Mock that self.instance2.submodel_set.all() returns [foreignKey2] def testSomething(self): self.assertEqual(self.instance1.get_max_value(), 1) self.assertEqual(self.instance2.get_max_value(), 2) ### models.py from django.db import models class MyModel(models.Model): def get_max_value(self): value = 0 # the return value of self.submodel_set.all() is what I want to mock for model in self.submodel_set.all(): value = max(value, model.my_value) return value class Submodel(models.Model): my_model = models.ForeignKey(MyModel, null=True, on_delete=models.SET_NULL) my_value = models.IntegerField() I tried several combinations of the @patch decorator, Mock() and MagicMock() but could not get it to work. Thank you in advance! -
Unable to import CSV table in a model on PostgreSQL
I am doing a project on Django with database connected to postgreSQL. I did all the commands related to models as makemigrations and migrate so my tables appear on PgAdmin 4 correctly. The problema is for a particular table "Dashboard_país" with 2 columns (id and nombre) I am not able to import csv table, when with the other models importing csv I didnt have any problem. My model Dashboard_país looks like this: class País(models.Model): nombre = models.CharField(max_length=100) class Meta: verbose_name = "País" verbose_name_plural = "Países" def __str__(self): return self.nombre I receive the next error when import my csv: Running command: --command " "\copy public."Dashboard_país" (id, nombre) FROM 'C:/Users/auxer/Desktop/pais.csv' DELIMITER ';' CSV HEADER ENCODING 'UTF8';"" Start time: Thu Oct 19 2023 10:50:53 GMT+0200 (hora de verano de Europa central) \copy: error de procesamiento al final de la l�nea Processing error at the end of the line or something similar on english. I was searching on the internet and didnt find anyone with a similar error so I would be glad if anyone could help me Thanks. I tried import a simple CSV like this: Id;Nombre 1;John 2;Emma 3;Michael but it didnt work I also tried using query tool but commands doesnt … -
Azure Entra + Django SSL to many redirect
I try to connect MS Entra with Azure App. Everything works great on local version but production fail. Depending on the options SECURE_SSL_REDIRECT=False I got AADSTS50011: The redirect URl http:/myapp/auth/redirect specified in the request does not match the redirect URl's configured for the application. Of course in app on Azure I can't set http only https work. If SECURE_SSL_REDIRECT=True and Debug=False I got: To many redirect error. Cookies clean, different computer same error. Local test work with http and runserver In production I use gunicorn 443 port and docker. Cookies clean, different settings and computer. Some advice with gunicorn setting I think -
sock=backend at=error code=H18 desc="Server Request Interrupted"
Issue is, in my api view have some logic, and when a request hit to endpoint, there is two thing happening one is oauth2_provider validating token and other is logic execution for request, so when token validation failes it gatting 403 and it raising heroku\routing sock=backend at=error code=H18 desc="Server Request Interrupted" error and end user getting response as 503 instead of 403. I have implemented token validation system, where i have used django-oauth-toolkit package and deployed on heroku platform. Here, we are having separate Authorization and resource server, i have configured resource server as below mentioned. INSTALLED_APPS = ( ... 'oauth2_provider',) OAUTH2_PROVIDER = { ... 'RESOURCE_SERVER_INTROSPECTION_URL': 'https://example.org/o/introspect/', 'RESOURCE_SERVER_AUTH_TOKEN': '3yUqsWtwKYKHnfivFcJu', # OR this but not both: 'RESOURCE_SERVER_INTROSPECTION_CREDENTIALS': ('rs_client_id','rs_client_secret'), ...} i have used class based view ProtectedResourceView how to avoid this Heroku code=H18 503 getting into end user response and capture 403 and send as end user response if token validation fails with 403. -
Django server is not running suddenly
I had many working projects and suddenly when I tried to run the server using the: python manage.py runserver, I get the following output, and the server doesn't run: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). I have seen similar questions, but in their case the problem was related to connecting to the database, but in my case I'm using sqllite and even tried to start new django project and run the server and I have faced the same issue.