Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need help running Django at a local machine after deploying it to DigitalOcean apps
I'm using Digital Ocean app platform to host my website but after following the settings from the end of this documentation from the website (at the end of step 2), there's something I think I'm missing cause I have deployed the app following the guide but now I can't run it on my local machine. The error comes from this snippet, throwing the Exception "DATABASE_URL environment variable not defined" elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic': if os.getenv("DATABASE_URL", None) is None: raise Exception("DATABASE_URL environment variable not defined") DATABASES = { "default": dj_database_url.parse(os.environ.get("DATABASE_URL")), } Any clue? I thought I should use something like python-dotenv or django-dotenv or having multiple Django settings modules, but my brain right now is just frosted. Please help -
Django ASGI/channels with Streaminghttpresponse
I add channels to my project and it's creating a problem, I have a stream func that streama video with streaminghttpresponse , and that work well before I add asgi/channels to run the server I saw that it's some bug that will be fixed in django 4.2 but I look for solution for now/ or if someone suggests another library for a socket that will now cause a similar problem this is my code Django v - 4.0 channels - 3.0.5 views.py def stream(source,startVideo): if startvideo : url = source + str('.mp4') cap = cv2.VideoCapture(url) while (cap.isOpened()): ret, frame = cap.read() if not ret: check = False break results = model(frame,augment=False,size=320) det = results.pred[0] results.render() annotator = Annotator(frame,line_width=2, pil=not ascii) im0 = annotator.result() image_bytes = cv2.imencode('.jpg', im0)[1].tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + image_bytes + b'\r\n') cap.release() cv2.destroyAllWindows() @csrf_exempt def video_feed(request): if request.method == 'POST': global startvideo,start,content startvideo=True content = request.GET.get('url','not') return StreamingHttpResponse(stream(content,startvideo), content_type='multipart/x-mixed-replace; boundary=frame') ASGI.PY application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket':AuthMiddlewareStack(URLRouter( webcam.routing.websocket_urlpatterns )) }) setting.py INSTALLED_APPS = [ 'channels', ...... 'webcam', ...... ] ASGI_APPLICATION = 'stream.asgi.application' routing.py websocket_urlpatterns = [ re_path(r'ws/socket-server/',consumers.ChatConsumer.as_asgi()), ] consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'test' await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def … -
Django form.instance.field displaying incorrect datetime value on HTML template despite having the correct value at hand
I'm running Django 4.1, and the view that serves the template is a FormView-child. To start off with, here's the canonical answer as to what the correct value is, taken directly from the database: In [6]: DCF.objects.last().appreciation_date Out[6]: datetime.date(2023, 1, 24) The first HTML template invocation of that same field: <h5>Title: {{ form.instance.appreciation_date }}</h5> And the result is as expected: About 30 lines of code below (none of which do anything particularly functional, it's just a boatload of div declarations for CSS and styling), inside a <form>, on a modal: <div class="mb-3"> <label for="{{ form.appreciation_date.id_for_label }}">Date</label> <input class="form-control datepicker" placeholder="Please select date" type="text" onfocus="focused(this)" onfocusout="defocused(this)" name="{{ form.appreciation_date.name }}" value="{{ form.instance.appreciation_date }}"> </div> And now, prepare for the result - which also highlights the question I am about to get to: What in Django's ghost in the shell is going on? How did 2023-01-24 become 2023-01-01 for no apparent reason? Or said differently, why and how can the same context invocation have two different values in the same render of the same template? I would very much like for the second invocation to show the correct value - meaning the value that is both in the database, and presumably also in … -
Django Form unexpected keyword argument
i have a form which contains a choiceField and i need to populate it from a view, so i'm trying to use the kwargs inside the init function like this : class SelectionFournisseur(forms.Form): def __init__(self,*args, **kwargs): super(SelectionFournisseur, self).__init__(*args, **kwargs) self.fields['Fournisseur'].choices = kwargs.pop("choixF",None) Fournisseur = forms.ChoiceField(choices = ()) my view : formF = SelectionFournisseur(choixF=choices) but i get the error BaseForm.__init__() got an unexpected keyword argument 'choixF' -
Django Unitest, can't recognize the error
I am wondering if could anyone help out here, I am trying to send a post request to the URL, but I am not sure about the best way of doing it? The idea here is to test the creation of the card object, but I am getting an error which I am not managing to figure out, if anyone could help me out here it would be fantastic. here the code and the error below it def test_create_card(self): payload = { 'title': "Sample card title", 'description': 'Get a free coffee for every 10 coffee you buy', 'points_needed': 10, } res = self.client.post(CARDS_URL, self.company, **payload) print(res) self.assertEqual(res.status_code, status.HTTP_201_CREATED) card = Card.objects.get(id=res.data['id']) for k, v in payload.items(): self.assertEqual(getattr(card, k), v) self.assertEqual(card.company, self.company) ERROR ERROR: test_create_card (card.tests.test_card_api.PrivateCardAPITests) Test creating a card Traceback (most recent call last): File "/app/card/tests/test_card_api.py", line 141, in test_create_card res = self.client.post(CARDS_URL, self.company, **payload) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 295, in post response = super().post( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 208, in post data, content_type = self._encode_data(data, format, content_type) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 179, in _encode_data ret = renderer.render(data) File "/py/lib/python3.9/site-packages/rest_framework/renderers.py", line 914, in render return encode_multipart(self.BOUNDARY, data) File "/py/lib/python3.9/site-packages/django/test/client.py", line 245, in encode_multipart for (key, value) in data.items(): AttributeError: 'Company' object has no … -
How properly request.user.is_superuser inside function in django admin.py
I am learning Djnago and I have this function inside admin.py that counts how many participants in an activity, it is working fine until, I want to know if the current user is a superuser and added request inside def set_count(self, request, obj) expecting to make a request for the user. Since I am getting an error, this means, this it's not how to do it and wrong. How to correct this? Thanks. Below is what I want to do, evaluate the user.is_superuser if true, it will display in the list_display the link to the participants_changelist otherwise, display a plain text. def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate(set_count=Count('activity_activity')) return queryset def set_count(self, request, obj): counter = obj.set_count if request.user.is_superuser: url = ( reverse("admin:activity_announcements_participants_changelist") + "?" + urlencode({"activity__id": f"{obj.id}"}) ) return format_html('<a href="{}">{} Paticipants</a>', url, counter) else: counter = obj.set_count return format_html('{} Paticipants', counter) set_count.short_description = "No. of Paticipants" Error: TypeError at /admin/activity_announcements/activity/ ActivityAdmin.set_count() missing 1 required positional argument: 'obj' Request Method: GET Request URL: http://localhost:8000/admin/activity_announcements/activity/ Django Version: 4.1.5 Exception Type: TypeError Exception Value: ActivityAdmin.set_count() missing 1 required positional argument: 'obj' Exception Location: /py/lib/python3.11/site-packages/django/contrib/admin/utils.py, line 280, in lookup_field Raised during: reversion.admin.changelist_view Python Executable: /py/bin/python Python Version: 3.11.1 Python Path: … -
datetime.datetime.now() is five minutes off
I'm currently developing a django backend. I use auto_now_add=True in my model to populate a start point on create(). I use datetime.datetime.now() to add an endpoint on update(). The entire code for that is datetime.datetime.now().replace(tzinfo=pytz.timezone(settings.TIME_ZONE). Here's an example for an instance that was created at 2023-01-21T19:26:04.561888Z and updated only seconds later. As you can see, the endpoint populated on update() is somehow before the startpoint, which is not intended behavior. Thank you -
Error while Installing Django on Visual Studio
I install Django on Visual studio but I have these errors enter image description here enter image description here Downloading virtualenv-20.17.1-py3-none-any.whl (8.8 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 8.8/8.8 MB 4.5 MB/s eta 0:00:00Collecting platformdirs<3,>=2.4 Downloading platformdirs-2.6.2-py3-none-any.whl (14 kB) Collecting filelock<4,>=3.4.1 Downloading filelock-3.9.0-py3-none-any.whl (9.7 kB) Collecting distlib<1,>=0.3.6 Downloading distlib-0.3.6-py2.py3-none-any.whl (468 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 468.5/468.5 KB 9.8 MB/s eta 0:00:00Installing collected packages: distlib, platformdirs, filelock, virtualenv WARNING: The script virtualenv.exe is installed in 'C:\Users\bienh\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed distlib-0.3.6 filelock-3.9.0 platformdirs-2.6.2 virtualenv-20.17.1WARNING: You are using pip version 22.0.4; however, version 22.3.1 is available. You should consider upgrading via the 'C:\Users\bienh\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe -m pip install --upgrade pip' command. PS C:\Users\bienh\OneDrive\Documents\Django> virtualenv env virtualenv : The term 'virtualenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + virtualenv env + ~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (virtualenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundExceptiontype here How to do this: "Consider adding this directory to PATH or, if you prefer to suppress … -
I'm struggling with coinbase, i want to make an app using django that accept users to buy coins with cyptocurrency
i was working in a project and the client ask me to add a way to let users buy coins (coins are the balance of the users so they can buy tickets) what i want is if someone can help me to know how to do it by using coinbase because it is not possible in my country to use another way -
AttributeError Exception: Serializer has no attribute request in DRF
I have written following code in serializer where I am validating data: class MySerializer(serializers.ModelSerializer): class Meta: model = models.MyClass fields = "__all__" def validate(self, data): role = data["role"] roles = models.Role.objects.filter( -->(exception) organization=self.request.user.organization ) if role not in roles: raise serializers.ValidationError("Invlid role selected") return data But I am getting following exception: 'MySerializer' object has no attribute 'request'. And it is coming in the mentioned line. I want to access current user in validate function. How can I do that? -
Nextjs React Rollup Module You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file
I have been trying everything I can find online to solve this error. Based on what I have read this module is configured correctly, but still errors. I am using yalc to link to the main project. Using npx rollup -c --bundleConfigAsCjs to compile. Error ./node_modules/test-wordpress/dist/index.d.ts Module parse failed: Unexpected token (3:8) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | import { sendForm } from "./ContactForm7"; | import { getPage } from "./Wordpress"; > declare const _default: { | getPage: typeof getPage; | sendForm: typeof sendForm; tsconfig.json { "compilerOptions": { "target": "es5", "jsx": "react", "module": "esnext", "sourceMap": true, "declaration": true, "outDir": "dist" }, "include": [ "src" , "src/index.tsx" ] } rollup.config.cjs import typescript from '@rollup/plugin-typescript'; export default { input: { Wordpress: 'src/Wordpress.tsx', ContactForm7: 'src/ContactForm7.tsx' }, output: { dir: 'dist', format: 'cjs', sourcemap: true, }, plugins: [ typescript() ], external: ['react'], }; package.json { "name": "test-wordpress", "version": "1.0.2", "description": "Wordpress test project", "main": "./dist/index.d.ts", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/test-project/wordpress.git" }, "author": "Paul Winter", "license": "ISC", "bugs": { "url": "https://github.com/test-project/wordpress/issues" }, "homepage": … -
In Django, is it possible to see which method is generating a SQL query?
When creating a custom User (inherits from AbstractUser) we have a signal which creates a randomized password (from Django's get_random_string) and send it out in an email in a celery task to the user: # signals.py @receiver(post_save, sender=User, dispatch_uid="c_employee") def create_employee(sender, instance: User, created, **kwargs): if not instance.has_usable_password(): password = get_random_string(length=12) email_args = { # we're collecting information for the celery task "password": password, } email_send_as_task.delay( email_args, "Sending PASSWORD CREATE email to {{ instance.email }}" ) if password: logger.debug(f"CREATE PASSWORD FOR INSTANCE: {instance}") sender.objects.filter(pk=instance.pk).update(password=make_password(password)) # .update so we don't trigger signal again And looking through my (logging level DEBUG) logs, I can see the following: D0121 18:55:35.434 accounts.signals:81 CREATE PASSWORD FOR INSTANCE: Employee @ Example D0121 18:55:35.641 django.db.backends:123 (0.000) UPDATE "accounts_user" SET "password" = 'pbkdf2_sha256$260000$FKRktQOZAwQ4OjcvD3QHGn$dmg9T1Y3mEwN1nbI5W2EyOAHp2chU4MGvSlaOTORNxY=' WHERE "accounts_user"."id" = 394; args=('pbkdf2_sha256$260000$FKRktQOZAwQ4OjcvD3QHGn$dmg9T1Y3mEwN1nbI5W2EyOAHp2chU4MGvSlaOTORNxY=', 394) So far so good. But then, later in the logs, this query appears: D0121 18:55:35.770 django.db.backends:123 (0.015) UPDATE "accounts_user" SET "password" = '', "last_login" = NULL, "is_superuser" = false, "username" = 'employee@example.com', "first_name" = 'First name', "last_name" = 'Employee', "email" = 'employee@example.com', "is_staff" = false, "is_active" = true, "date_joined" = '2023-01-21T17:55:35.044046+00:00'::timestamptz, "company_id" = 20, "venue_id" = 297, "avatar" = 'users/avatar.jpg', "is_admin" = false, "is_developer" = true, "role" = 'event', … -
Django third-party library views: determining async vs sync
I want to incorporate async into my Django library. If I have a Django library that has 1) a sync view and 2) a urls.py that points to that sync view, how do I support both sync and async? Presumably, I could ask the developer to set a setting to LIBRARY_ENABLE_ASYNC, then in views.py, I could write: from django.conf import settings if settings.LIBRARY_ENABLE_ASYNC async def view(request): pass else: def view(request): pass But that doesn't seem quite... right? Admitedly, I believe because we integrate with the Django ORM, we'll be splitting the views into two separate files/directories/and urls.py files, and the developer would simply include() the correct urls.py based on whether they're using ASGI/WSGI, but in the event the above does happen, is there a better way to determine whether a user is using ASGI/WSGI? -
Django multi-language does not load the custom-translated files when changing the user language but only works when LANGUAGE_CODE explicitly set
when I change the language of the user by URL or calling translation.activate(lang_code) only the default texts are translated and the custom translation that I created not loading, but if I change the LANGUAGE_CODE to the target language in the settings file the translation shows without any issue. but I want when to change the user language show the custom translations that I create its my model: from django.db import models from django.utils.translation import gettext as _ class Test(models.Model): test = models.CharField( max_length=100, verbose_name=_("test text"), ) my admin: from django.contrib import admin from lng.models import Test @admin.register(Test) class TestModelAdmin(admin.ModelAdmin): ... my settings: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', "django.middleware.locale.LocaleMiddleware", # Here ! 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ BASE_DIR / 'locale/', ] my urls : from django.urls import path ,include from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] translatable_urls = [ path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns(*translatable_urls) my project structure: . ├── db.sqlite3 ├── lng │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py … -
Using if statement in django template to detect a NULL
My web application stores dances and the YouTube link to that dance. The table shows the dance name and a link to the video which is passed to a new page to show the embedded video. This all works fine but some dances do not have a video and the return from the database for video_id is NULL.as below http://localhost:8000/video_test/HjC9DidEwPc,%20Big%20Blue%20Tree --- with video or http://localhost:8000/video_test/NULL,%20Baby%20Kate ---- with no video I want include a test for the null in the template which tabulates the dances so that the link does not appear if no video tabulated output is the word video is a link to video_test Column A Column B The dance name Video The dance name Video I have tried using {% if i.video == NULL %} is NULL, is None, but none work.I have looked at various other questions which seem to suggest that one of the above should work. I either get an unable to parse error or the if statement has no effect. . Model class Dances(models.Model): name = models.CharField('name', max_length=120) video_id = models.CharField('video_id', max_length=50) level = models.CharField('level', max_length=3) def __str__(self): return str(self.name) view def video_test(request, id, name): vid_id= id d_name = name return render(request, 'alineapp/video_test.html',{'vid_id':vid_id, 'd_name':d_name}) … -
how to display in models img to html in django
I tried to display to html changeable profile image with admin. can someone explain please models in Portfolio app : class ProfileImage(models.Model): profile = models.ImageField(("Profile image"), upload_to=None, height_field=None, width_field=None, max_length=None) this is base html in template folder (i tried this one) : <img src="{{ portfolio.models.ProfileImage.progile.url }}" alt="profile"><br /> -
Increment field value by 1 from the last value if a boolean field is checked - Django
I have a simple model of application: class Application_data(Models.model): application_sn=models.AutoField(primary_key=True) applicant_name=models.CharField(max_length=20) sanction_sn=models.IntegerField(default=0) is_sanctioned=models.BooleanField(default=False) In this model, I may have multiple applications, not sanctioned. I want that if I set is_sanctioned as true,sanction_sn gets incremented by 1, and for the next random row from the db, if I set the boolean as true, sanction_sn gets again incremented by 1, i.e. 2. And setting boolean as False should also decrease the values of sanction_sn, accordingly. For example: in a set of 130 rows, at 124th sanction_sn, I set the boolean as False, so 123 records before that particular record, have no effect at all but after 123, 125th record will have sanction_sn as 124 and 130th record will have sanction_sn as 129. -
Install Django on Visual studio
I install Django on Visual studio but I have these errors enter image description here How to do this: "Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location." Could you please help me to fix them? Thank you very much -
django-filter finds a match if you enter the full name
django-filter finds a match if you enter the full name. For example, I try to filter by the name "Titanic" and I type "Titan" into the search, nothing will be found until I type in the entire text "Titanic". How do I search by partial match? class ProjectFilter(django_filters.FilterSet): address__name = django_filters.CharFilter(field_name='address', lookup_expr='street') approve = django_filters.BooleanFilter(field_name='approve') ordering = django_filters.OrderingFilter(choices=CHOICES, required=True, empty_label=None,) class Meta: model = Project exclude = [field.name for field in Project._meta.fields] order_by_field = 'address' View class FilterTable(SingleTableMixin, FilterView): table_class = TableAll model = Project template_name = "table.html" filterset_class = ProjectFilter -
Optimizing DRF performance
I am trying to optimize a DRF view that has very low performance, is there a way to make it faster? This is where I am right now Models: class CategoryVideos(models.Model): class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return f"{self.name} and {self.id}" class Videos(models.Model): category = models.ManyToManyField(CategoryVideos, null=True, blank=True) illustration = models.FileField(null=True, blank=True) video = models.FileField(null=True, blank=True) title = models.CharField(max_length=255, null=True, blank=True) description = models.CharField(max_length=255, null=True, blank=True) url_video = models.CharField(max_length=255, null=True, blank=True) url_image = models.CharField(max_length=255, null=True, blank=True) Serializers: class CategorySerializer2(serializers.ModelSerializer): class Meta: model = CategoryVideos fields = ["name"] class VideoSerializer(serializers.ModelSerializer): category = CategorySerializer2(many=True, read_only=True) class Meta: model = Videos fields = ["id", "description", "title", "url_video", "url_image", "category"] read_only=True View: class OfferListAPIView(generics.ListAPIView): queryset = Videos.objects.prefetch_related('category').all() serializer_class=VideoSerializer For the moment, with 400 videos and just 6 categories, it takes approx 2.8 secs to get an answer which is way too high. Many thanks -
Django Rest How do I call objects that are under my reference object?
I cannot call the movies under a Director. I want to make a page where you click the name of the director and it will show the list of movies that are directed by the director. What shown below is the codes for models, serializers, and views. models.py class Director(models.Model): _id = models.AutoField(primary_key=True) firstname = models.CharField(max_length=100, null=True, blank=True) lastname = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return "%s %s" % (self.firstname, self.lastname) class Product(models.Model): _id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) description = models.TextField(null=True, blank=True) director = models.ForeignKey(Director, on_delete=models.CASCADE) def __str__(self): return self.name serializers.py class ProductSerializer(serializers.ModelSerializer): director = serializers.StringRelatedField() class Meta: model = Product fields = '__all__' class DirectorSerializer(serializers.ModelSerializer): class Meta: model = Director fields = '__all__' views.py @api_view(['GET']) def getProducts(request): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(_id=pk) serializer = ProductSerializer(product, many=False) return Response(serializer.data) @api_view(['GET']) def getDirector(request): director = Director.objects.all() serializer = DirectorSerializer(director, many=True) return Response(serializer.data) I already tried what is shown above. -
Django namespacing still produces collision
I have two apps using same names in my django project. After configuring namespacing, I still get collision. For example when I visit localhost:8000/nt/, I get page from the other app. (localhost:8000/se/ points to the right page). I must have missed something. Here is the code: dj_config/urls.py urlpatterns = [ path("se/", include("simplevent.urls", namespace="se")), path("nt/", include("nexttrain.urls", namespace="nt")), # ... ] dj_apps/simplevent/urls.py from . import views app_name = "simplevent" urlpatterns = [ path(route="", view=views.Landing.as_view(), name="landing") ] dj_apps/nexttrain/urls.py from django.urls import path from . import views app_name = "nexttrain" urlpatterns = [ path(route="", view=views.Landing.as_view(), name="landing"), ] dj_config/settings.py INSTALLED_APPS = [ "dj_apps.simplevent.apps.SimpleventConfig", "dj_apps.nexttrain.apps.NexttrainConfig", # ... ] Note that reversing order of apps in INSTALLED_APPS will reverse the problem (/se will point to nexttrain app). -
Can you convert a Django 'DateField()' to 'date'?
I was using the 'DateField()' in Django, and I wanted to find the time between two dates that are stored in the 'DateField()' field. How can I do this? This is what I was trying originally: length = datetime.timedelta(start, end) It gives me this error: TypeError: unsupported type for timedelta seconds component: DateField -
Django with flutter
How to do Django backend for flutter app if I don't know flutter? I expect the guidance on how can I do the backend project of flutter in Django without having knowledge in flutter. -
SerializerMethodField and circular import
I need help with REST Framework. I have to do my test for internship position and I have two models with circular import 'Pokemon' model and 'Team' mode. In serializer of 'Team' I have this code class TeamDetailsSerializer(ModelSerializer): """Serializer for details of Team instances""" pokemon_1 = SerializerMethodField() pokemon_2 = SerializerMethodField() pokemon_3 = SerializerMethodField() pokemon_4 = SerializerMethodField() pokemon_5 = SerializerMethodField() trainer = UserSerializer() class Meta: model = Team fields = ( "trainer", "name", "pokemon_1", "pokemon_2", "pokemon_3", "pokemon_4", "pokemon_5", ) read_only_fields = ("id",) # Methods to relate each Pokemon object def get_pokemon_1(self, obj): pokemon_1 = obj.pokemon_1 if not pokemon_1: return None serializer = pokemon.serializers.PokemonDetailsSerializer(pokemon_1) return serializer.data def get_pokemon_2(self, obj): pokemon_2 = obj.pokemon_2 if not pokemon_2: return None serializer = pokemon.serializers.PokemonDetailsSerializer(pokemon_2) return serializer.data def get_pokemon_3(self, obj): pokemon_3 = obj.pokemon_3 if not pokemon_3: return None serializer = pokemon.serializers.PokemonDetailsSerializer(pokemon_3) return serializer.data def get_pokemon_4(self, obj): pokemon_4 = obj.pokemon_4 if not pokemon_4: return None serializer = pokemon.serializers.PokemonDetailsSerializer(pokemon_4) return serializer.data def get_pokemon_5(self, obj): pokemon_5 = obj.pokemon_5 if not pokemon_5: return None serializer = pokemon.serializers.PokemonDetailsSerializer(pokemon_5) return serializer.data and problem that I get this kind of schema name* [...] trainer* User{...} pokemon_1 integer nullable: true pokemon_2 [...] pokemon_3 [...] pokemon_4 [...] pokemon_5 [...] but I would like to get object …