Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
About machine learning to identify plant growth cycles
I want to train a simple one that can identify the growth cycle of plants in pictures, such as seedling stage or mature stage. I tried to find some data sets, but I didn't figure out how to implement it. Please tell me if you have any good ideas or if you have the ability, I will give you a certain reward cais201219@gmail.com -
ModuleNotFoundError: No module named '—'
Am attempting to deploy a Django app on Digital Ocean's Droplet. I have gunicorn, nginx, postgresql and my domain ip connected. However, am unable to load the site when I visit the domain. Running - sudo tail -f /var/log/gunicorn_supervisor.log (venv) root@pmkattorneys-droplet:/var/www/pmkattorneys# sudo tail -f /var/log/gunicorn_supervisor.log return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked ModuleNotFoundError: No module named '—' [2024-08-07 07:50:23 +0000] [396636] [INFO] Worker exiting (pid: 396636) [2024-08-07 07:50:23 +0000] [396635] [ERROR] Worker (pid:396636) exited with code 3 [2024-08-07 07:50:23 +0000] [396635] [ERROR] Shutting down: Master [2024-08-07 07:50:23 +0000] [396635] [ERROR] Reason: Worker failed to boot. nginx error 2024/08/07 07:50:53 [crit] 381423#381423: *355 connect() to unix:/var/www/pmkattorneys/web.sock failed (2: No such file or directory) while connecting to upstream, client: 194.28.224.213, server: pmkattorneys.com, request: "GET /.env HTTP/1.1", upstream: "http://unix:/var/www/pmkattorneys/web.sock:/.env", host: "104.131.178.60" Anyone else has expereienced this ? Your help is highly appreciated I tried downgrading my oython ftom 3.12 to 3.6 and back to 3.12. Deleted the virtual env and recreated it. -
CORS header on OPTIONS request?
I am trying to set up a webapp with Angular and Django but I have a problem with the CORS headers. As far as I understand, in order to include cookie data from the frontend in the request (such as csrf token and session id), I need to set the withCredentials to true in the request. So a GET request looks like this.http.get(this.url, { withCredentials: true });. Then the browser says Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at xxx. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’). I can fix this for the GET request by adding the header to the response with response["Access-Control-Allow-Credentials"] = "true", but the problem comes when I make a POST request. In this case the frontend automatically sends an OPTIONS request before the POST, which as far as I understand is standard and is used to check what the backend allows to be posted. However, I can't set the CORS header for the response of the OPTIONS request, so in effect I can't send a POST request. Is there a way to set the header for OPTIONS responses or am I doing something wrong in general? -
Issue with sending JSON Array in multipart/form-data from POSTMAN
I've been struggling with writable serialises in DRF and I keep having this issue: "music_preferences": [ "Incorrect type. Expected pk value, received list." ], "artists": [ "Incorrect type. Expected pk value, received list." ] I'm building an endpoint that is supposed to allow an admin to create an event. This is the serializer: class EventCreateSerializer(serializers.ModelSerializer): music_preferences = serializers.PrimaryKeyRelatedField(queryset=Music.objects.all(), many=True, write_only=True) artists = serializers.PrimaryKeyRelatedField(queryset=Artist.objects.all(), many=True, write_only=True) event_picture = serializers.ImageField(required=False) # Made optional class Meta: model = Event fields = ( 'name', 'start_date', 'end_date', 'venue', 'minimum_age', 'vibe', 'public_type', 'dresscode', 'music_preferences', 'event_picture', 'artists', ) def create(self, validated_data): music_preferences_data = validated_data.pop('music_preferences') artists = validated_data.pop('artists') # Check if event_picture is provided, else use the venue's image if 'event_picture' not in validated_data or not validated_data['event_picture']: venue = validated_data['venue'] validated_data['event_picture'] = venue.venue_picture # Use venue_picture from the venue event = Event.objects.create(**validated_data) # Set music preferences event.music_preferences.set(music_preferences_data) event.artists.set(artists) return event This is the view in which it is invoked: def post(self, request, venue_id): data = request.data.copy() # Add files to the data dictionary if 'event_picture' in request.FILES: data["event_picture"] = request.FILES["event_picture"] data['music_preferences'] = json.loads(data['music_preferences']) data['artists'] = json.loads(data['artists']) serializer = EventCreateSerializer(data=data) if serializer.is_valid(): event = serializer.save() event_data = EventCreateSerializer(event).data event_data['id'] = return Response({ 'data': event_data }, status=status.HTTP_201_CREATED) # Log serializer … -
Showing django static images on emails
I am trying to send an email with django static images on my emails like using {% static "path_to_img" %}, but that's not working. Then I tried giving the image it's full path by giving the url and the domain in my view, but that's not working either. My mail.html: <!DOCTYPE html> {% load static %} <html> <head> <title>Order Rejected</title> </head> <body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; color: #333; background-color: #f5f5f5;"> <div style="background-color: white; padding: 20px; border: 1px solid #ddd;"> <header style="margin-bottom: 20px;"> <img src="{{ request.build_absolute_uri }}{% static 'event/images/logo.svg' %}" alt="img" style="height: 30px;"> </header> <div style="text-align: center; margin-bottom: 20px;"> <img src="{{ request.build_absolute_uri }}{% static 'event/images/order_rejected.png' %}" alt="Order Status" style="width: 80%; max-width: 400px;"> </div> <h1 style="font-size: 24px; margin-bottom: 5px;">Order Rejected</h1> <p style="margin-bottom: 20px;">Order number: #{{ order.ref_code }}</p> <p style="margin-bottom: 20px;">Hi {{ order.user.first_name }},<br> We regret to inform you that your order has been rejected. The full amount has been refunded to your original payment method. If you have any questions, please email us at info@everyeventaus.com.au.</p> <a href="#" style="display: block; background-color: #8B0000; color: white; text-align: center; padding: 10px; text-decoration: none; margin-bottom: 20px;">Log into account</a> <div style="background-color: #333; color: white; padding: 10px; margin-bottom: 10px;"> <h2 style="margin: 0; font-size: … -
Restrict IP access to the Django admin deployed on Render app
Good day, community. I am developing a Django application for an online store, where the seller will publish their products through the admin panel, and customers will see the products through views and templates. While I was developing locally, there was no problem accessing the admin panel since I was running it from my PC. However, now that I have deployed the application on Render app, I've just realized that I can access the admin panel by appending 'admin/' to the URL. How can I restrict access to the admin panel to certain IPs, like a firewall, meaning only my IP can access the admin panel? Please help me I have the starter plan -
Django - Assigning employee to projects on various dates (durations)
How can I assign each employee (many) on projects (many) while also tracking the dates when they were assigned and removed from each project? I realize this is a ManyToManyField type of relationship in Django where: class Project(models.Model): projectname=models.CharField() class Employee(models.Model): firstname = models.CharField() lastname = models.CharField() start_date = models.DateField(null=False) end_date = models.DateField(null=True) #because we don't know this all the time projects = models.ManyToManyField(Project) But I hope to be able to generate an app where I can both view each employee where they are on projects currently and where they've been in the past. The tricky part here consists in me possibly sending employees back to the same project after having taken them off for a couple of weeks to perform on another project. Please forgive me for this is my first post/question on this site and haven't quite grasped the proper format for asking questions. I simply tried adding a start_date and an end_date for each employee but I do not think that is working properly as I have a feeling those dates are overwritten every time I modify Employee. I am missing something and hope to find others more experienced that would see the easy solution here. -
A more elegant approach to writing Django’s unit tests
I am currently writing tests using Django’s unit tests (based on Python standard library module: unittest). I have written this test for my Contact model which passes: class ContactTestCase(TestCase): def setUp(self): """Create model objects.""" Contact.objects.create( name='Jane Doe', email='janedoe@gmail.com', phone='+2348123940567', subject='Sample Subject', message='This is my test message for Contact object.' ) def test_user_can_compose_message(self): """ Test whether a user can compose a messsage in the contact form.""" test_user = Contact.objects.get(name='Jane Doe') self.assertEqual(test_user.email, 'janedoe@gmail.com') self.assertEqual(test_user.phone, '+2348123940567') self.assertEqual(test_user.subject, 'Sample Subject') self.assertEqual(test_user.message, 'This is my test message for Contact object.') Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). . ---------------------------------------------------------------------- Ran 1 test in 0.005s OK Destroying test database for alias 'default'... However, I had to use the assertEqual method 4 times in this test (could be more when testing models with more fields). It seems like this doesn't follow the DRY principle. I know from the docs that assertEqual(first, second, msg=None) tests that first and second are equal. If the values do not compare equal, the test will fail. Is there a workaround or a more elegant approach to writing such tests? -
Make list of list populated by Django or MYSQL query filtered by column's name
I'm not very good in Django or Mysql so please be tolerant, I have this table in my DB named table_bdc (Simplified version) I would like to iterate through the DB to create a list of list with a query depending on the column's name last digit (_1 or _2 or _3 and so on). Something like : final_list = [] for i in range(2) result = models_bdc.objects.raw("SELECT * FROM table_bdc WHERE id='1' AND column name ends with RLIKE %s",["_"+(i+1)]) final_list.append(result) For example with the first line (id 1), the expected result would be : final_list = [[3,4],[6,7]] I already searched the forum to learn and get to this point but the rest is still too complex for me yet ... Can someone please show me how to do this ? PS: The DB cannot be refactored or changed I have to deal with it this way. Thanks -
Typescript output directory setup
I need help to setup my tsconfig.json file. I'm building a Django project with multiple apps, the base structure for what I would like to obtain is as follow: project/ |-app1/ | |-app2/ | |-tsconfig.js Now, each app folder should have this structure: appX/ |-static/ |-appX |-js/ | |-test.js | |-ts/ |-test.ts Basically I want my tsconfig to output the relative js file always inside "../js/", and this has to be true for any app of the project. Is this possible to achieve? I have tried to change outDir but I can't build it so that it takes into consideration a generic relative path. For example, using ../js simply creates the javascript files inside in a folder on the same level as "project" -
Python Django, using external MSSQL database
I'm trying to make a django website that connects to an external MSSQL database to retrieve information only (read-only). This database is huge with hundreds of tables. I can currently get it to work by creating a function in my django app that uses the connectionString and runs a raw SQL query and returns it in a pandas dataframe. Somehow I feel this is not how Django should be used. Can you please guide me on how to do this in the proper Django way. I think I need to use models? but this is an external database and I don't want to write anything to it. I also don't want to have to define all the table names in my models, but I will if I have to. Can you please guide me on how to go about this while making sure the database stays as read-only? How do I structure my settings.py,How do I structure my models.py,How do I structure my views.py to be able to interact with the db? import pyodbc import pandas as pd def SQL_to_df(driver,server,database,user,password,query): connectionString = pyodbc.connect(f"Driver={driver};Server{server};Database={database};UID={user};PWD={password};") df = pd.read_sql(query, connectionString) return df -
If statement django template correct construction
Could someone help me to find the correct way to construct the template in django. If the view object is edited by moderator (user is not owner) I put into context an object that has permissions as attributes. For example, object.permission_profile is boolean field that allows to edit user-owner profile. So, in template I suggest I need to use if-statement to put necessary url, one url - when both object exists and permission is True, and another url - if object is not in context. I put into template if-statement such way {% if object %} {% if object.permission %} url-1 {% endif %} {% else %} url-2 {% endif %} Is this correct way? Or is there another right or faster rule to use it? Thank you! -
How to optimize method with multiple query calls?
I have an event system in my app. Every time a user deletes/updates/creates and object a new event is created in the database with the info of the object and the type of event it is. My Event model looks something like this: class Event(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) model = models.CharField(max_length=200) object_id = models.IntegerField() event_type = enum.EnumField(ModelEventType) In this model, model is the name of the object's model, and object_id is the ID of that object. My app also has multiple access permissions: some objects are private to the user, while others are shared among teammates. Thus, I need to restrict events to only those that correspond to a user's access level. To fetch each user's events, I retrieve all objects the user has access to, obtain their IDs, and then fetch the events related to those objects. I use a method like this to fetch the objects belonging to a user: class Event(models.Model): .... @staticmethod def get_events_ids(request): object_ids = {} Object1 = apps.get_model("myapp", "Object1") Object2 = apps.get_model("myapp", "Object2") Object3 = apps.get_model("myapp", "Object3") Object4 = apps.get_model("myapp", "Object4") Object5 = apps.get_model("myapp", "Object5") objects1 = Object1.objects.filter(...) objects2 = Object2.objects.filter(...) objects3 = Object3.objects.filter(...) objects4 = Object4.objects.filter(...) objects5 = Object5.objects.filter(...) objects = … -
TypeError: ForeignKey(None) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
I am not new to Django but I am to Apache. I recently developed a web app and tested its deployment on Nginx and it worked just fine. The client has a preference for Apache though and I created a config file. After this, I am getting a 500 server error and the error above is presenting itself. Below is part of the traceback in the Apache error log: [Tue Aug 06 19:48:10.945075 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "<frozen importlib._bootstrap>", line 688, in _load_unlocked [Tue Aug 06 19:48:10.945077 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "<frozen importlib._bootstrap_external>", line 883, in exec_module [Tue Aug 06 19:48:10.945079 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed [Tue Aug 06 19:48:10.945082 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "/var/www/mysite/vir/lib/python3.10/site-packages/django/contrib/admin/models.py", line 48, in <module> [Tue Aug 06 19:48:10.945086 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] class LogEntry(models.Model): [Tue Aug 06 19:48:10.945089 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "/var/www/mysite/vir/lib/python3.10/site-packages/django/contrib/admin/models.py", line 54, in LogEntry [Tue Aug 06 19:48:10.945090 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] user = models.ForeignKey( [Tue Aug 06 19:48:10.945092 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "/var/www/mysite/vir/lib/python3.10/site-packages/django/db/models/fields/related.py", line 959, in __init__ [Tue Aug 06 19:48:10.945094 2024] [wsgi:error] [pid … -
request BETWEEN in fastapi orm
async def get_all( self, session: AsyncSession, order_field: str | None = 'created_at', is_desc: bool | None = False, **param ): if order_field is not None: if is_desc: k = desc(order_field) else: k = order_field else: k = 'created_at' objs = await session.scalars(select(self.__model).filter_by(**param).order_by(k)) return objs.all() I have legacy code that returns all objects from the database. Im need to change the code, or create a new method to return objects whose registration date is between two datetime dates. At the moment, I'm just clinging to all the objects and cutting off unsuitable data in the code, but this option is clearly not optimal at all. In django orm, everything is somehow simple, but here I have scoured the entire Internet and have not found any built-in options in order to implement this. Thank you in advance for your help <3 -
ModuleNotFoundError at /accounts/login/ No module named 'allauth.forms'
Iam trying to add allauth login and signup in my project and getting this error *ModuleNotFoundError at /accounts/login/* *No module named 'allauth.forms'* This is the traceback ` Traceback (most recent call last): File "/var/data/python/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/utils/decorators.py", line 48, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/decorators.py", line 12, in wrap resp = function(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/utils/decorators.py", line 48, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/views/decorators/debug.py", line 143, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/utils/decorators.py", line 48, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/views/decorators/cache.py", line 80, in _view_wrapper response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/account/views.py", line 84, in dispatch return super().dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/account/mixins.py", line 40, in dispatch response = super().dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/account/mixins.py", line 59, in get response = super().get(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/views/generic/edit.py", line 142, in get return self.render_to_response(self.get_context_data()) ^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/account/views.py", line 102, in get_context_data ret = super().get_context_data(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/account/mixins.py", line 122, in … -
Strange Behavior with Django Serializers [closed]
Hey i'll try to summerize the current situation: i believe the higher level scope of this method isn't really required to understand the situation as the problem lays between syntax? or just bad programming on my part: i have this method: it's exact working are not really useful as it is being created to make an unclear request possible, on a poorly written structure (not my doing) in the first part i am creating an instance of FasiPrestazionali via the Serializer, subsequently i save that instance and copy it inside a variable fase_instance as fase_id late i successfully use it here: commessa.fase_prestazionale.add(fase_id) now i want to know why i by repeating the same thing with just a different model fase_id = fase_instance.id django tells me that fase_instance.id does not exist? class PreventivoStudioForm(generics.ListCreateAPIView): queryset = PreventivoStudio.objects.all() serializer_class = PreventivoStudioSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] #primo caso in presenza di commessa_id : creare un PreventivoStudio con i dati forniti e ciclare le fasi rendendole ciascuna una fasePrestazionale legata alla commessa fornita def post(self, request, *args, **kwargs): studio_id = request.data.get("id") commessa_id = request.data.get("commessa_id") if commessa_id: commessa = Commesse.objects.get(id=commessa_id) studio = Studio.objects.get(id=studio_id) #riassociazione di 'fasi' dentro la request per ciclarli come FasiPrestazionali fasi … -
Django model's relationships and fetching related data from database
I'm having a hard time finding a decent explanation about this in django's official documentation, so I'll ask my question here. in django 5.0 if two models have a relationship (let's call them Model1 and Model2) with whether a OneToOneField, ForeignKey or ManyToManyField , when you fetch some objects from the database with a query like this : data = Model1.objects.filter(field1=value) do the Model2 objects related to the objects in data (which are of the type Model1) get fetched and joined to the queryset automatically? note that the relationship might be of any type (one-to-one , many-to-one, many-to-many) and can be a reverse or forward relationship. if the answer to my question depends on the type of relationship between two objects, please explain all the possible cases. if you know where exactly I can read about this, please leave me a link. I've tried asking a bunch of AIs about this but they just confused me with contradictory answers. -
how to override a google auth screen with a custom template
I want a custom template in the url http://accounts/google/login. How do I do it.I just want some stying in it with CSS. Suggest a stepwise solution.Should I try custom template but where do i place it and what to name it. I want to remove the menu div. I have no idea what to do. so i tried nothing -
Django Form request.POST.get() returning None in terminal
So I'm trying to retrieve one element from a form but everytime I get None as value instead of a name for example. Below the form html : <form method="post" action="/contact"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" aria-describedby="name" placeholder="Enter your name"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="Phone">Phone</label> <input type="phone" class="form-control" id="Phone" placeholder="Enter your phone number"> </div> <div class="form-group"> <label for="text">Text</label> <input type="text" class="form-control" id="Description" placeholder="Enter your message"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> And my view.py : def contact(request): if request.method =='POST': print(request.POST.get('name')) return render(request, 'contact.html') Any tips or ideas on how to solve this ? Thanks -
Hosting Django Web Application as an application on an existing website
I hosted a django web app on IIS using wfastcgi and it was successful when hosted as a new website using the configuration details below. What would I need to do differently on these configurations if I want to host the very app as an application to an existing IIS website on production. I have tried copying the very configuration and placing it it in the root of the IIS application but finding error 500 - internal server error. The IIS user already has read, execute and edit permissions on the app folder. <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="WSGIHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\pathtopython\Scripts\python.exe|C:\pathtowfastcgi\Scripts\wfastcgi.py" resourceType="Unspecified" /> </handlers> <rewrite> <rules> <rule name="Django" stopProcessing="true"> <match url=".*" /> <action type="Rewrite" url="http://localhost:8000/{R:0}" /> </rule> </rules> </rewrite> </system.webServer> </configuration> -
pytest Database access not allowed
I am trying to run my tests with access to an existing database to reuse it. Here is the error: ERROR drf/tests/test_auth.py - RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. here is the pytest.ini [pytest] DJANGO_SETTINGS_MODULE = drf.tests.test_settings python_files = test_*.py django_debug_mode = true pythonpath = .venv/bin/python addopts = --reuse-db --create-db here is the test_settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR + '/tests', 'dump_test.sql'), } } Here is a simplified version of the test: @pytest.mark.django_db class AuthTestCase: def test_two_step_authentication(self): user = UsersFactory.create() # Initialize the API client client = APIClient() # Step 1: Authenticate the user to get the initial token url_step1 = reverse('token-auth-s1') credentials = { 'email': user.email, 'password': 'password123' } response_step1 = client.post(url_step1, credentials, format='json') # Assert the response status code assert response_step1.status_code == 200 The directory structure: drf ├── drf │ ├── __init__.py │ ├── settings.py │ ├── tests │ │ ├── __init__.py │ │ ├── dump_test.sql │ │ ├── factory_boy │ │ │ ├── __init__.py │ │ │ ├── factory_models.py │ │ │ └── languages_factory.py │ │ ├── test_auth.py │ │ └── test_settings.py ├── manage.py └── pytest.ini List of things I have … -
It becomes to array when sending djang nested dict to API
I sent the dict data with this in python data = { "test":{ "A":"Adata", "B":"Bdata", "C":"Cdata" } } response = self.client.post("/api_patch/",data,follow=True) then receive this as @api_view(["POST","GET"]) def api_patch(request): print("request.data",request.data) print("request.data type",type(request.data)) However this shows, request.data <QueryDict: {'test': ['A', 'B', 'C']}> request.data type <class 'django.http.request.QueryDict'> some how A B C is treated as array. Where am I wrong?? -
Foreignkey Django separator
There is a model: class Categories(models.Model): name = models.CharField(max_length=150, unique=True, verbose_name='Name') slug = models.SlugField(max_length=200, unique=True, blank=True, null=True, verbose_name='URL') class Products(models.Model): name = models.CharField(max_length=150, unique=True, verbose_name='Name') slug = models.SlugField(max_length=200, unique=True, blank=True, null=True, verbose_name='URL') category = models.ForeignKey(to=Categories, on_delete=models.PROTECT, verbose_name='Categoy') I don't understand how to make it so that in Products I could write category_id separated by commas. That is, so that one product would have different categories. Are there any separator arguments for Foreignkey? For example, I will show my idea with pseudocode category = models.ForeignKey(to=Categories, on_delete=models.PROTECT, separator=';') -
Manually Adding Swagger Documentation Does Not Show Example Values in Responses Section
I have a simple django rest API project with some endpoints. I have installed swagger API documentation for viewing and testing APIs. as you know the APIs that are dependent on models and serializers will be added to the swagger documentation automatically and there is no problem with them. I have another view which is not related to a model or serializer so I wrote the swagger code for it manually. now the problem I faced is that the example values of the Responses section in this endpoint are not loaded and a circle is just turning! here is the code and the image of swagger: import requests from django.shortcuts import render from store.models import Customer from .serializers import CustomerSerializer from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema class Verification(APIView): @swagger_auto_schema( request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'phone': openapi.Schema(type=openapi.TYPE_STRING, description='Phone number to verify'), 'token': openapi.Schema(type=openapi.TYPE_STRING, description='Verification token sent via SMS') }, required=['phone', 'token'] ), responses={ 200: openapi.Response( description='Successful verification', examples={ 'application/json': { 'status': True, 'detail': '200, your entered token matched.', } } ), 400: openapi.Response( description='Invalid input or verification failed', examples={ 'application/json': { 'status': False, 'detail': …