Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How deploy django application on your own company server?
I have a django application ready to go for production but my company gave me a suggestion which is having there own server and deployed there and honestly I have no clue how to acheive this. Any help with specific details would be highly appreciated -
I am getting IntegrityError NOT NULL constraint failed: login_new_user.sturesidance
In my template I have defined it like this, ` <!-- residance --> <div class="input-group mb-2 "> <span class="input-group-text w-25" for="residance">Residence</span> <input class="form-control text-bg-primary bg-opacity-10 text-dark text-opacity-50" type="textarea" name="stureisidance" cols="4" rows="5" placeholder="type current address" required> </div> ` In my models i have this filed . ` sturesidance=models.TextField() ` This is how I created my object, ` new_user.objects.create( stuname= stuname, stubirthday= stubirthday, stuphoto= stuphoto , stugemail= stugemail ,stugrade= stugrade , stuclass= stuclass,stuentrance= stuentrance , sturesidance= sturesidance ,stuguardian= stuguardian , stugtele= stugtele , stumother= stumother ,stumothertele= stumothertele ,stuotherskills= stuotherskills ,stucertificate= stucertificate ,stuletter= stuletter ,stumedical= stumedical ,stusports= stusports ,stupassword= stupassword ) ` Now I am getting error IntegrityError Exception Value: NOT NULL constraint failed: login_new_user.sturesidance -
<int:pk> or {pk} does not work in DRF router
I have an Comment which have an Article foreign key (so Article have an "array" of comments). I need to build an url to fetch theese comments using article's pk, but when I am trying to do smth like "articles/int:article_pk/comments/" or "articles/{article_pk}/comments/" drf router crates static route with path "articles/{article_pk}/comments/". How can I implement getting a comments using article pk? -
Cannot install mysqlclient for my Django project using pip on ZorinOS
Im new in Django. I am using python3.11.0 and pip 22.3.1 in django framework. I want to use mariaDB in my Django project. For that I have to install mysqlclient. I tried a lot of things, but it doesn't work. This error is coming when I try: pip install mysqlclient Output: (venv) kiril@noknow-PC:~/Work/django_project/mysite$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [44 lines of output] mysql_config --version ['8.0.31'] mysql_config --libs ['-L/usr/lib/x86_64-linux-gnu', '-lmysqlclient', '-lpthread', '-ldl', '-lssl', '-lcrypto', '-lresolv', '-lm', '-lrt'] mysql_config --cflags ['-I/usr/include/mysql'] ext_options: library_dirs: ['/usr/lib/x86_64-linux-gnu'] libraries: ['mysqlclient', 'pthread', 'dl', 'resolv', 'm', 'rt'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,1,'final',0)"), ('__version__', '2.1.1')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-311 creating build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-cpython-311/MySQLdb creating build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py … -
Why Django throws an error creating test database?
When I try to run tests on my Django project, it throws the following error creating the test database: django.db.utils.ProgrammingError: relation "users_websiteuser" does not exist If I run the project, everything works fine. I've already tried running all the migrations (makemigrations and then migrate) and deleting the test database, but it still doesn't work. How can I fix this? -
Django admin can't create records for model with self-referential foreign key
This is my model: class Customer(models.Model): name = models.CharField(max_length=100, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) referee = models.ForeignKey('self', on_delete=models.RESTRICT, blank=True, null=True) def __str__(self): return self.name When I try to create a customer via admin site I got this error: TypeError at /admin/customer/customer/add/ Field 'id' expected a number but got <Customer: my_customer_name>. How can I fix this? Thank you. -
Django, PgBouncer and DigitalOcean, How to work DB Connection Pools
I'm using digitalocean managed database with django. How to create connection pool? -
Is there a way to add custom data into ListAPIView in django rest framework
So I've built an API for movies dataset which contain following structure: Models.py class Directors(models.Model): id = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'directors' ordering = ['-id'] class Movies(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100, blank=True, null=True) year = models.IntegerField(blank=True, null=True) rank = models.FloatField(blank=True, null=True) class Meta: db_table = 'movies' ordering = ['-id'] class Actors(models.Model): id = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) gender = models.CharField(max_length=20, blank=True, null=True) class Meta: db_table = 'actors' ordering = ['-id'] class DirectorsGenres(models.Model): director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='directors_genres') genre = models.CharField(max_length=100, blank=True, null=True) prob = models.FloatField(blank=True, null=True) class Meta: db_table = 'directors_genres' ordering = ['-director'] class MoviesDirectors(models.Model): director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='movies_directors') movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_directors') class Meta: db_table = 'movies_directors' ordering = ['-director'] class MoviesGenres(models.Model): movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_genres') genre = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'movies_genres' ordering = ['-movie'] class Roles(models.Model): actor = models.ForeignKey(Actors,on_delete=models.CASCADE,related_name='roles') movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='roles') role = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'roles' ordering = ['-actor'] urls.py from django.urls import path, include from . import views from api.views import getMovies, getGenres, getActors urlpatterns = [ path('', views.getRoutes), path('movies/', getMovies.as_view(), name='movies'), path('movies/genres/', getGenres.as_view(), name='genres'), path('actor_stats/<pk>', getActors.as_view(), name='actor_stats'), ] serializer.py from … -
Editing in Django admin reversed depended by foreign key
How in class QuestionsAdmin(admin.ModelAdmin) implement that in Django admin in Question can see all, add, edit and delete all Answers? class Answer(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) value = models.TextField() correct = models.BooleanField() question = models.ForeignKey("Questions", models.DO_NOTHING) class Question(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) content = models.TextField() -
First argument to get_object_or_404() must be a Model. How can I get an user's id to the User model?
I'm trying to make a favorite functionality where an user can add other users as their favorites. In the View where the profile of an user is shown I have a button that adds an user or removes it if it was already added. The problem is that I can't pass to the views the user that will be added as a favorite. models.py class User(AbstractUser): is_type1 = models.BooleanField(default=False) ... class Type1(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) favorite = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, related_name='favorite') views.py def FavoriteView(request, pk): current_user = request.user Type1.user = current_user.id buser = Type1.user Type1.favorite = get_object_or_404(User, id=request.POST.get('username')) # The of the error where I try to add the user being added as a favorite fuser = Type1.favorite if Type1.favorite.filter(id=request.user.id).exists(): Type1.favorite.remove(request.user) else: Type1.favorite.add(request.user) return HttpResponseRedirect(reverse('profile-details', kwargs={'username': Type1.favorite})) class UserView(DetailView): model = User ... template_name = 'users/profile-details.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) favorite_connected = get_object_or_404(Type1.favorite, id=self.kwargs['username']) # The of the error where I try to add the user being added as a favorite favorite = False if favorite_connected.favorite.filter(id=self.request.user.id).exists(): liked = True data['user_is_favorite'] = favorite return data profile-details.html ... {% if user.is_authenticated %} <form action="{% url 'favorite' object.id %}" method="POST"> {% csrf_token %} {% if user_is_favorite %} <button type="submit" … -
Django Queryset to search for article title
I aim to search for the article title using a query set, I am following this 'basic filtering' guide however it doesn't work for me. terminal traceback- AttributeError: 'DeferredAttribute' object has no attribute 'filter' views.py class SearchResultsView(ListView): model = Article template_name = 'search_results.html' queryset = Article.title.filter(name__icontains='1st') I tried using queryset = Article.objects.filter(name__icontains='1st') however this resulted in the below which is why I used 'title' rather than 'objects' File "/Users/Lucas/Python/Projects/news/.venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1677, in names_to_path raise FieldError( django.core.exceptions.FieldError: Cannot resolve keyword 'name' into field. Choices are: author, author_id, body, comment, date, id, title models.py class Article(models.Model): title = models.CharField(max_length=225) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse("article_detail", kwargs={"pk": self.pk}) I looked at this but can't get it to work. Also tried the documentation. If i remove the query set line at the bottom of the class the search function returns all of the values as per the below .html file. Which displays all the article content but without any filters of course. search_results.html <ul> {% for article in article_list %} <li> {{ article.title }}, {{ article.body }} {{ article.date }}{{ article.author }} </li> {% endfor %} </ul> Am I missing … -
Does anyone know if i can add an image upload function to a form with cloudinary?
I'm building a Django blog in which i want registered users to be able to create their own blog posts including a title image. i've incorporated cloudinary but can currently only upload images through the admin panel. After reading through the docs and a few similar questions here i am none the wiser. Has anyone encountered anything like this? Is it possible to just put an image upload in my form and tie that in to cloudinary somehow? please help! -
Django serializer returns empty dictionary on create
I have this model that basically joins two different users: class Couple(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) user1 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=False, related_name="user1" ) user2 = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=False, related_name="user2" ) def __str__(self): return str(self.id) What I did next, was create a Serializer where user1 invites user2 to create a couple. And I want to do this by writing user2 email address: class CreateCoupleSerializer(serializers.Serializer): partner_email = serializers.EmailField(write_only=True, max_length=250, required=True) def create(self, validated_data): partner_email = validated_data['partner_email'] try: partner = User.objects.get(email=partner_email) except Exception: partner = None if not partner: raise serializers.ValidationError( {"details": 'User does not exist'}) if partner.couple_id: raise serializers.ValidationError( {"details": 'User is already assigned to a couple'}) user = self.context['request'].user couple = Couple.objects.create(user1=user, user2=partner) user.couple_id = couple.id partner.couple_id = couple.id user.save() partner.save() return couple And this is my view: class CreateCoupleView(generics.CreateAPIView): serializer_class = CreateCoupleSerializer queryset = Couple.objects.all() By testing this I can see that the Couple is being created, which is great! However, in my body response, I'm getting an empty dictionary instead of the new couple instance. My question is why is this happening? Bonus question: When should I create logic in def create() from the Serializer side vs def create() on the View side? … -
Annotate on reverse many-to-many
I'm trying to work out why this doesn't work:- class A(models.Model): contacts = models.ManyToManyField(Contact) class Contact(models.Model): name = models.CharField() If I try and get a count of how many A there are with multiple contacts:- A.objects.annotate(num_contacts=Count('contacts')).filter(num_contacts__gt=1).count() there are 10. but if I have a particular contact and I want to get a count of how many A's they are connected to that have more than 1 contact on them:- B.a_set.annotate(num_contacts=Count('contacts')).filter(num_contacts__gt=1).count() I get 0. The num_contacts count always comes out as 1, even when the A has more than 1 contact. I must have missed something silly but I can't see it. Any ideas? -
django select_for_update(nowait=False) in transaction.atomic() does not work as expected
I have a django app that needs to get a unique ID. Many threads run at the same time that need one. I would like the IDs to be sequential. When I need a unique ID I do this: with transaction.atomic(): max_batch_id = JobStatus.objects.select_for_update(nowait=False).aggregate(Max('batch_id')) json_dict['batch_id'] = max_batch_id['batch_id__max'] + 1 status_row = JobStatus(**json_dict) status_row.save() But multiple jobs are getting the same ID. Why does the code not work as I expect? What is a better way to accomplish what I need? I cannot use the row id as there are many rows that have the same batch_id. -
"No such table" error coming from serializers.py file, when running migration command
I recently moved my Django app from using the default User model to a custom User model, and since this is not recommended to do mid-way through a project, I had to drop the database and migrations and recreate migrations and run migrate. This works fine when I comment out the entire serializers.py file, as well as comment out everywhere it is referred to. However, now that I want to be able to action all the new migration steps at production level WITHOUT having to comment out serializers.py. I know that I have referenced a table that doesn't technically exist so, I'm just wondering what is the best way to do this? Here is my serializers.py code: class MyModelSerializer(serializers.Serializer): features = Feature.objects.values_list("feature_name", flat=True) # Feature is a model feature = serializers.ChoiceField(features) # this is where the error happens The error says: "no such table: myapp_feature" -
Best way to store multiple date in one object django
I have model Topic. Now i have date = models.DateTimeField class Topic(models.Model): owner = models.ForeignKey(Profile, on_delete=models.SET(GUEST_ID)) seminar = models.ForeignKey(Seminar, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(default='') speaker_name = models.CharField(max_length=200, default='') date = models.DateTimeField(null=True, blank=True) but i want to save multiple date for example: 27.11.2022,29.11.2022,01.01.2023. I have idea to write date = models.CharField() and save dates as string Is there a better solution? -
Django DateTimeField Timestamp value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format
The environment is: Django 4.0 (venv) Python 3.8 Postgres 15 Elementary OS 6.1 The initial model: class MyModel(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Upon saving a new record (without providing any value for "created" nor "updated") the result was: django.core.exceptions.ValidationError: ['“1669827388000” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] Then I've followed some suggestions to do this: class MyModel(models.Model): created = models.DateTimeField(editable=False) updated = models.DateTimeField(editable=False) # Still doesnt work: It gets a timestamp def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() self.updated = timezone.now() return super(Token, self).save(*args, **kwargs) The result was exactly the same (of course the timestamp's value changed). I've tried variations with django.settings settings.USE_TZ from True to False & vice versa. Traceback: Traceback (most recent call last): File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) … -
How to assign multiple api views to single endpoint in django rest framework?
I have a model named Article and a few api views for it. They are divided for diffrent purposes (for example ArticleUpdateAPI class for UPDATE http method, ArticleDeleteAPI for DELETE method etc). In urls.py they are separated to diffrent endpoints (aritcle/pk/update, /article/pk/delete etc). As I know, it's not good practice to build endpoint like this, so I want to bind them to single url and use diffrent classes for handling diffrent http methods. Is it possible and how? Examples are below ArticleAPI.py class ArticlePostAPI(generics.CreateAPIView): serializer_class = ArticleSerializer permission_classes = [ permissions.IsAuthenticatedOrReadOnly ] def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "comment": CommentSerializer.data }, status=201) class ArticleRetrieveAPI(generics.RetrieveAPIView): serializer_class = ArticleSerializer queryset = Article.objects.all() permission_classes = [ permissions.AllowAny ] class ArticleListAPI(generics.ListAPIView): serializer_class = ArticleSerializer queryset = Article.objects.order_by('number', 'headline') permission_classes = [ permissions.AllowAny ] class ArticleUpdateAPI(generics.UpdateAPIView): serializer_class = ArticleSerializer queryset = Article.objects.all() permission_classes = [ permissions.IsAuthenticated ] lookup_field = 'pk' def update(self, request, *args, **kwargs): instance = self.get_object() if request.user != instance.author: return Response({ "errors": "Logged in user and author must be same" }, status=403) serializer = self.get_serializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) urls.py urlpatterns = [ ... # Article API path('article/post/', ArticlePostAPI.as_view(), name='article_creation'), path('article/<int:pk>/', ArticleRetrieveAPI.as_view(), name='article_retrieve'), path('article/', … -
Django Rest Framwork : Nested objects in one serializers
I have double nested serializer situation... i have three models : Reports, ReportPages and widgets , upon trying to create a specific endpoind that is : payload { "since_date": "some date", "until_date": "some other date that is greater than since_date", "report_pages": [ { "page_number": "some number" (generated from front end, of type integer) "widgets": [ { "data": ["some array"], "width": "some number", "height": "some number", "top_position": "some number", "left_position": "some number", "widget_type": "" (either "Label", "LineChart", "Bar" or "PieChart"), } ] } ] } I faced a problem with nested serializer, i was only able to create the first half which is : payload { "since_date": "some date", "until_date": "some other date that is greater than since_date", "report_pages": [ { "page_number": "some number" (generated from front end, of type integer) ] } Knowing that the creation of a report is separate from this endpoint, so i override the update method and structure looks like this : Report{ report_page{ widgets {} } } My models : class Reports(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=500, null=True) since_date = models.DateTimeField(null=True) until_date = models.DateTimeField(null=True) def __str__(self): return self.name class ReportPages(models.Model): id = models.AutoField(primary_key=True) number = models.IntegerField(null=True) report = models.ForeignKey(Reports, related_name="report_pages",on_delete=models.CASCADE) def __str__(self): return self.number … -
Make an hourly booking system using Django
I wish to create an hourly booking system in Django. I need some help regarding it : 1) I need to send text to mobile number (Free service because I can't invest money right now) ==> I have used Twilio but it can't send message to unverified numbers on basic plan 2) for booking I need to take time input of hour : ==> how can I take time input on hourly basis, It can be done as spread sheet way(how https://in.bookmyshow.com accepts seat booking) but I am unable to figure it out For frontend I'm using Bootstrap5 for sending text to mobile number I tried Twilio but it can't send text to unverified numbers on basic plan. -
Django CountryField, query by country
I have a class similar to this: class Person(models.Model): name = CharField(max_length=255) citizenship = CountryField(multiple=True) In this example a Person can have more than one citizenship. Person.objects.create(name="Fred Flinstone", citizenship="US, CA") I want to query for everyone who has a US citizenship, which would return Fred from above. Is there a django-countries way to do this? I suppose I could treat it like a CharField. If I wanted to do something more complex like "is Person a citizen of US or GB", I was hoping there was a nicer way than a complex CharField query. -
Django user is_authenticated vs. is_active
After reading the documentation, I still don't fully grasp the difference between these two User methods: is_authenticated and is_active. Both are returning a boolean. While is_authenticated is read-only (and you get an error if you try to set it), is_active can be modified and for instance you can set it to False instead of deleting account. Running these commands, will de-activate a user: >>> from django.contrib.auth.models import User >>> u = User.objects.get(pk=10) # get an arbitrary user >>> u.is_active True >>> u.is_active = False # change the value >>> u.save() # save to make effective >>> u.is_authenticated True Now, this user is still authenticated but is not able to login anymore. The login view uses authenticate(). What is actually happening that the login for a de-activated user fails? if request.method == 'POST': username = request.POST['username'] password = request.POST['password1'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) To verify the credentials you use authenticate() which returns a User object in case of success or None otherwise. I guess it returns None in case the supplied credentials are correct but is_active is False. In addition, the Jinja block {% if user.is_authenticated %} evaluates as false if is_active is … -
Customise json output, returning first item from list on Django Rest Framework
I have an API that returns the following json: { "id": 6, "lot_no": "787878", "product_id": "116110", "assay_type": "reascan_crp", "valid_from": "2022-11-21", "expiry_date": "2022-11-27", "is_active": true, "last_modified": "2022-11-21T14:29:32.435307Z", "teststrips": [ { "number": 1, "name": "", "control_line_threshold": 1.0, "testlines": [ null, null ] } ], "parameters": [ { "a": -3.0, "b": -4.0, "c": -6.0, "d": -9.0 } ] }, however I want the following output without the list on parameters: { "id": 6, "lot_no": "787878", "product_id": "116110", "assay_type": "reascan_crp", "valid_from": "2022-11-21", "expiry_date": "2022-11-27", "is_active": true, "last_modified": "2022-11-21T14:29:32.435307Z", "teststrips": [ { "number": 1, "name": "", "control_line_threshold": 1.0, "testlines": [ null, null ] } ], "parameters": { "a": -3.0, "b": -4.0, "c": -6.0, "d": -9.0 } }, serializers.py : class ParametersSerializer(serializers.ModelSerializer): class Meta: model = TeststripConfiguration fields = ('a', 'b', 'c', 'd') class TeststripSerializer(serializers.ModelSerializer): testlines = serializers.SerializerMethodField() class Meta(): model = TeststripConfiguration fields = ('number', 'name', 'control_line_threshold', 'testlines') def get_testlines(self, teststrip): upper_negative_testline = None lower_positive_testline = None if str(teststrip.batch.assay_type) != "reascan_crp": upper_negative_testline = teststrip.testlines.values('upper_negative_threshold')[0]['upper_negative_threshold'] lower_positive_testline = teststrip.testlines.values('lower_positive_threshold')[0]['lower_positive_threshold'] return upper_negative_testline, lower_positive_testline class BatchSerializer(serializers.ModelSerializer): parameters = ParametersSerializer(source='teststrips', many=True, read_only=True) teststrips = TeststripSerializer(many=True, read_only=True) assay_type = serializers.SlugRelatedField( read_only=True, slug_field='name' ) product_id = serializers.ReadOnlyField() class Meta(): model = Batch fields = ('id', 'lot_no', 'product_id', 'assay_type', 'valid_from', 'expiry_date', 'is_active', 'last_modified', … -
Half of the dropdown is hidden
I made a django app with a navbar. On the right corner, it has a user area with some things, like profile and logout area. This user area is a dropdown, and when it's activated it goes outside the navbar. dropdown error I tried several things, like adding "dropdown-menu-right" but nothing worked, it's probably some stupid mistake I made and I can't figure it out. Can you help me ? navbar <nav class="navbar navbar-expand-lg navbar-dark bg-dark"style="width: 100%;" id="navbar"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home' %}">Plataforma</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> {% if user.is_authenticated %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Documentos </a> <ul class="dropdown-menu mr-auto"> <a class="dropdown-item" href="{% url 'carregar-documentos'%}">Carregar</a> <hr class="dropdown-divider"> <a class="dropdown-item" href="{% url 'download-documentos'%}">Download</a> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Dados</a> <ul class="dropdown-menu dropdown-menu-right"> <a class="dropdown-item" href="{% url 'list_triturador'%}">Triturador</a> <hr class="dropdown-divider"> <a class="dropdown-item" href="{% url 'atualizar'%}">Atualizar</a> {% url 'list_triturador' as sitio %} {% if request.path == sitio %} <a class="dropdown-item" href="{% url 'triturador_csv'%}">Exportar Excel</a> {% endif %} {% else %} {% endif %} </ul> </li> </ul> <!-- Dropdown Error --> <ul …