Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Present Python variable in HTML Template in Django
I have a value extracted from JIRA API showing a total for a particular project. When I print the value, I can see the correct values and these are clearly being stored in the variable. # Emergency Changes Query jira_emergency_changes = jira.search_issues('labels = new-emerging-audit AND resolution = Unresolved').total # Open Issues Query jira_open_issues = jira.search_issues('project = UTILITY AND status = Open').total # Open JIRA Ticket Total Query jira_open_tickets = jira.search_issues('project = "UTILITY" AND status not in (Closed, Completed, Resolved) ORDER BY created DESC').total I want to add these values to a template page in a <p> tag, but no matter what method I try, it just doesn't render. Could some advice? :) -
ssl error with copying file in s3 server?
I tried to collect static files on the S3 Server for my Django project with the command : python manage.py collectstatic But It failed because of SSLError : During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\botocore\httpsession.py", line 414, in send chunked=self._chunked(request.headers), File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 756, in urlopen method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2] File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\util\retry.py", line 507, in increment raise six.reraise(type(error), error, _stacktrace) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\packages\six.py", line 769, in reraise raise value.with_traceback(tb) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 706, in urlopen chunked=chunked, File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 382, in _make_request self._validate_conn(conn) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 1010, in _validate_conn conn.connect() File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connection.py", line 421, in connect tls_in_tls=tls_in_tls, File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\util\ssl_.py", line 450, in ssl_wrap_socket sock, context, tls_in_tls, server_hostname=server_hostname File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\util\ssl_.py", line 493, in _ssl_wrap_socket_impl return ssl_context.wrap_socket(sock, server_hostname=server_hostname) File "C:\Users\Anthony\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 423, in wrap_socket session=session File "C:\Users\Anthony\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 870, in _create self.do_handshake() File "C:\Users\Anthony\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 1139, in do_handshake self._sslobj.do_handshake() urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1091) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute … -
django get related names for object
we can access to an object's all field by __dict__ class Profile(models.Model): chips = models.PositiveIntegerField(default=0) user = models.OneToOneField(User, on_delete=models.CASCADE) desc = models.CharField(max_length=255, default='', blank=True, null=True) image = models.ImageField(default='profile/default.jpg', upload_to='profile') active = models.BooleanField(default=False) points = models.PositiveIntegerField(default=0) createTime = models.DateTimeField(default=now, editable=False) email = models.EmailField(blank=True, null=True) Profile.objects.all()[0].__dict__ """ { '_state': <django.db.models.base.ModelState object at 0x7fe6d9632390>, 'id': 1, 'chips': 100000, 'user_id': 1, 'desc': None, 'image': 'profile/default.jpg', 'active': False, 'points': 100010, 'createTime': datetime.datetime(2022, 3, 13, 13, 45, 57, 513699, tzinfo=<UTC>), 'email': None } """ But does not include reference from ForeignKey, OneToOneField and ManyToManyField, that was defined on other models that has a related name. for example class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="articles") # __dict__ of Profile object does not include articles is there a way I can get all callable attributes of database from the model. thanks very much. -
Django - Update a model field through a form
I have this model which represents the values users submit through a form when making an applying for sponsorship. class ApplicationData(models.Model) : class Status(models.TextChoices): REJECTED = 'Rejected' PENDING = 'Pending' ACCEPTED = 'Accepted' """Define table for Applications in database""" user = models.ForeignKey(User, on_delete=models.DO_NOTHING) organisationName = models.CharField(max_length=200, null=True, blank=True) projectTitle = models.CharField(max_length=200, null=True, blank=True) CH_OSCR_number = models.CharField(max_length=20, unique=True, blank=True, null=True, ) projectDesc = models.TextField(max_length=300, null=True, blank=True) userGroupDesc = models.TextField(max_length=300, null=True, blank=True) learningOpp = models.TextField(max_length=300, null=True, blank=True) keyPartnersWork = models.TextField(max_length=300, null=True, blank=True) projImpactClimate = models.TextField(max_length=300, null=True, blank=True) projSupportLocBus = models.TextField(max_length=300, null=True, blank=True) proContribution = models.TextField(max_length=300, null=True, blank=True) length = models.IntegerField(null=True, blank=True) application_complete = models.BooleanField(default=False) date_of_application = models.DateField(null=True, blank=True) reviewed = models.BooleanField(default=False) app_status = models.TextField(choices = Status.choices, default = Status.PENDING) On the system there are 3 different user types. Once an applicant submits an application the staff users can view the submitted application details on a dedicated page. What I'm trying to do is to add a form on that page where the staff will have the ability to change the status of the application (app_status on the model). Here are my efforts: Here the is the form to update the field. class UpdateAppStatus(forms.ModelForm): class Meta: model = ApplicationData fields = ('app_status',) labels … -
How to have a ManyToManyField with two tables Sellers and Products
I have a Products Table class Products(models.Model): name = models.CharField(max_length=60) price= models.IntegerField(default=0) How to proceed with ManyToManyField between Sellers and Products -
TypeError: cannot use a string pattern on a bytes-like object python3
I have updated my project to Python 3.7 and Django 3.0 Here is code of models.py def get_fields(self): fields = [] html_text = self.html_file.read() self.html_file.seek(0) # for now just find singleline, multiline, img editable # may put repeater in there later (!!) for m in re.findall("(<(singleline|multiline|img editable)[^>]*>)", html_text): # m is ('<img editable="true" label="Image" class="w300" width="300" border="0">', 'img editable') # or similar # first is full tag, second is tag type # append as a list # MUST also save value in here data = {'tag':m[0], 'type':m[1], 'label':'', 'value':None} title_list = re.findall("label\s*=\s*\"([^\"]*)", m[0]) if(len(title_list) == 1): data['label'] = title_list[0] # store the data fields.append(data) return fields Here is my error traceback File "/home/harika/krishna test/dev-1.8/mcam/server/mcam/emails/models.py", line 91, in get_fields for m in re.findall("(<(singleline|multiline|img editable)[^>]*>)", html_text): File "/usr/lib/python3.7/re.py", line 225, in findall return _compile(pattern, flags).findall(string) TypeError: cannot use a string pattern on a bytes-like object How can i solve my issue -
Signing up users returning no attribute action error
I have an API handling the login and signup process (Django to React front end). While users can login, receiving an access and refresh token when I point towards the signup endpoint I get the error 'RegisterApi' object has no attribute 'action' Here is a breakdown of my code api.py: from rest_framework import generics, permissions, mixins from rest_framework.response import Response from .serializers import RegisterSerializer, UserSerializer from django.contrib.auth.models import User from rest_framework.permissions import AllowAny #Register API class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "message": "User Created Successfully. Now perform Login to get your token", }) #allow for anonymous signup def get_permissions(self): if self.action == 'create': return [AllowAny()] else: return super().get_permissions() def get_authenticators(self): if self.action == 'create': return [] else: return super().get_authenticators() serializers.py from django.contrib.auth.models import User from rest_framework import serializers #added more imports based on simpleJWT tutorial from rest_framework.permissions import IsAuthenticated from django.db import models from django.contrib.auth import authenticate from django.contrib.auth.hashers import make_password #changed from serializers.HyperLinked to ModelSerializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User #removed url from fields fields = ['username', 'email', 'password'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = User.objects.create_user(validated_data['username'], … -
Django custom admin filter: get filtered queryset before the current filter itself is applied
I have a classic admin.SimpleListFilter. I would want to get the current filtered/displayed queryset, but before my own filter is applied, so I can show the result count for each of my filter lookups. The current code below always shows total counts of each lookup, not respecting eventual other selected filters. class ByAssignementStatusFilter(admin.SimpleListFilter): title = _('Assignement Status') parameter_name = 'status__exact' def lookups(self, request, model_admin): choices = [] qs = model_admin.get_queryset(request) # qs.count() is always the unfiltered amount for key, label in Assignement.STATUS_CHOICES: count = qs.filter(assignement__status=key).count() label = f"{label} ({count})" choices.append((key, label)) return choices def queryset(self, request, queryset): if self.value() is not None: return queryset.filter(assignement__status=self.filter_value) else: return queryset -
How to deserializer two Models in django?
i'm sending two serializer models to api.py file... it is sending successfully but how to de-serializer both models in api.py views.py from django.http import HttpResponse, response from api.serializer import ResultsDNSerializer, ClassesExamMaxMarksSerializer, ResultSerializer, BlogPostsSerializer from rest_framework.renderers import JSONRenderer def ShowStudentResultAPI(request, id,eid): # Here id is Unique id of ResultDelcareNotice's Model and eid is ePunjabID of student Result_Delcare_Data = ResultsDeclareNotice.objects.filter(ID=id).first() Get_SessionCode = Result_Delcare_Data.SessionCode Get_AnnResultCode = Result_Delcare_Data.AnnResultCode Get_MonthCode = Result_Delcare_Data.MonthCode # Here AnnualResults is Model and here just we are fetching data stu_Data = AnnualResults.objects.get(SessionCode=Get_SessionCode,AnnResultCode=Get_AnnResultCode,MonthCode=Get_MonthCode,EID=eid) ResultDataTerm1 = AnnualResults.objects.filter(SessionCode=Get_SessionCode,AnnResultCode=Get_AnnResultCode,MonthCode=Get_MonthCode,EID=eid).first() StudentClassTerm1 = ResultDataTerm1.ClassCode Class_MaxMarksData = ClassesExamMaxMarks.objects.get(SessionCode=Get_SessionCode, ClassCode=StudentClassTerm1,AnnResultCode=Get_AnnResultCode) serializer = ResultSerializer(stu_Data) json_data = JSONRenderer().render(serializer.data) serializer_class_marks = ClassesExamMaxMarksSerializer(Class_MaxMarksData) json_data_class_marks = JSONRenderer().render(serializer_class_marks.data) Serializer_list = [json_data, json_data_class_marks] return HttpResponse(Serializer_list) import requests URL = "http://localhost:8000/api/result/1/4474239/" req = requests.get(url = URL) data = req.text print(data) -
Django ORM filter model where all relation have value equals to
Lets say that I have two models: class Worker(models.Model): name = models.CharField(max_length=100) class Task(models.Model): worker = models.ForeignKey(Worker) name = models.CharField(max_length=100) I would like to retrieve all workers where ALL tasks are called "dig". But I dont want workers that have only one Task called "dig". I've tried using filter and exclude with Q, like this: Worker.objects.filter(task__name='dig').exclude(~Q(task__name='dig')) But it didn't work, it don't remove those that have only one task like that. I could iterate over worker and tasks to find it, but is there any way to make this query using only orm? -
Django for each form input has its error message below it
I want to add error message for each input not all messages below each others if there is more than one message any help ? context = { 'error': False } if not email: messages.add_message(request, messages.ERROR, "Enter an Email", extra_tags='not_email') context['error'] = True I tried using extra_tags but also it viewed all the messages -
Django channels + Postgresql: Real-Time Database Messaging
I am currently developing an app with Django and PostgreSQL. Often, new information is sent to database (sometimes one time a day, sometimes over 30000 times a day). I have an UI (vue.js) and I want to see the data from the database showing to the client in real time. Currently I am using Django Channels. I implemented websocket and used psycopg2 library to listen to notifications from postgresql triggers. My consumer looks like this: class WSConsumer(WebsocketConsumer): def connect(self): self.accept() #the whole table is sent to the client after the connection self.send(json.dumps(ClientSerializer(Client.objects.all(), many=True).data)) #connecting to database conn = psycopg2.connect(dbname='...', user='...') conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) curs = conn.cursor() curs.execute("LISTEN update_clients_table;") #then I listen to any new data in this table and send it to the client while True: if select.select([conn],[],[],5) == ([],[],[]): print("Timeout") else: conn.poll() while conn.notifies: notify = conn.notifies.pop(0) print("Got NOTIFY:", notify.pid, notify.channel, notify.payload) message = notify.payload self.send(message) def disconnect(self): self.close() This is an example of handling changes in 1 table. I have 20 tables in total, and around 100 clients that can connect to the websocket. My question: is it a good way of building real-time app with Django and PostgreSQL? Is it simple, convenient, secure? Are there other ways to build … -
Could not parse the remainder: '(0,10)' from 'range(0,10)' with python
I have a problem with my template especially at the line: {% for j in range(0,10) %} I get the error: Could not parse the remainder: '(0,10)' from 'range(0,10)' -
how do I save form data from a different url template
how do I not save the form data until the transaction is done which is in a different URL, if the shipping form and the payment options were to be in the same URL then there wouldn't be this problem but it's not so how do I go about this? thx! views.py def checkout(request): if request.method == 'POST': form = ShippingForm(request.POST) if form.is_valid(): new_shipping = form.save(commit=False) new_shipping.customer = customer new_shipping.order = order #how do I not save the data until the transaction is successful new_shipping.save() return redirect('store:checkout_shipping') else: form = ShippingForm() else: form = ShippingForm() context = {"form": form} return render(request, 'shop/checkout.html', context) def checkout_payment(request): return render(request, 'shop/checkout_payment.html', context) urls.py path('checkout', views.checkout, name="checkout"), path('checkout_payment', views.checkout_payment, name="checkout_payment"), forms.py class ShippingForm(forms.ModelForm): address_one = forms.CharField(max_length=200) address_two = forms.CharField(max_length=200) -
Django favourite permission
how to configure permissions to receive favorites only of the user who added, and the favorites of other users could not be read models.py class Task(models.Model): user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') title = models.CharField(max_length=100) text = models.TextField(max_length=10000) class Favourite(models.Model): task_id = models.ForeignKey(Task, on_delete=models.CASCADE, blank=True, null=True, related_name='favourites',name='taskId') user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') views.py class FavouriteUserView(generics.ListAPIView): serializer_class = FavouriteReceivingSerializer pagination_class = MyCursorPagination permission_classes = (IsAuthor,) def get_queryset(self): return Favourite.objects.filter( userInfo_id=self.kwargs.get('pk')).select_related('userInfo').order_by('userInfo_id') permissions.py class IsAuthor(BasePermission): def has_permission(self, request, view): if request.method in SAFE_METHODS: return True return request.user and request.user.is_authenticated def has_object_permission(self, request, view, obj): return obj.userInfo == request.user -
Django drf-yasg swagger required header LOCALE parameter for every route
Is it possible to make header locale parameter required for every URL in application. Can i achieve it to set it up in global configuration or in every view method and if yes how can i do this? -
What is the best practice to store big sparse matrices in a django project?
I am finishing a public transport project that is using Dijkstra's algorithm. The algorithm is using adjacency matrices, with amount of nodes exceeding thousands -> propably going to scale this 10-100x, my matrices are sparse - <10% of non-zero values. The data is supposed to be updated once a day and is read-only. Since each of these values are evaluated multiple times per search, right now, I store non-zero values in the database, then create a matrix and save it as json file(n-lists of n-values), which is open and read every time the algorithm is run. What is the best practice to store and load this type of data? Should I store non-zero values the same way and just create sparse matrices with numpy and save it as HDF5 files? Would the HDF5 files introduce reading latency? I would like the final project to consist of 20-50k nodes, grouped into 1-5k matrices for each city and to be able to withstand something along the lines of a search a second. -
TypeError: Object of type Restaurant is not JSON serializable!!! Please tell me I am writing tests for drf, I get such an error
class CreatePizzaTestt(APITestCase): def setUp(self): self.restaurant = Restaurant.objects.create(name='Print', address='1') Restaurant.objects.create(name='Print12', address='1') self.valid = { 'restaurant': self.restaurant, 'pizza': 'Muffin', 'cheese': 'Muffin', 'dough': 'Pamerion', 'ingredient': 'White' } def test_restaurant_create(self): response = self.client.post( reverse('create_pizza'), self.valid) self.assertEqual(response.status_code, status.HTTP_201_CREATED) -
Django filter qs contains filename not working with underscores
my goal is to filter if the name of an uploaded document contains a search (a simple string from an input field submitted by the user). Strangely this works for long substring but not for short ones. Example My filter query is the following: Tab.objects.filter(document__file__icontains=search) where Tab is in simplest form a Model class like: class Tab(models.Model): name = models.CharField(max_length=50) and Document is another Model class wit a relation to Tabs and a file field. class Document(models.Model): tab = models.ForeignKey(Tab, on_delete=models.CASCADE) file = models.FileField(upload_to=custom_location) Weird behavior I've uploaded a file called example_test_123.pdf and if my search = example_test or test_123.pdf it results in a hit like expected. However, if search = test the filter doesn't find the file. Is this behaviour known or am I missing something here? Is it possible that the built-in name file is doing some trouble? Thanks. (Django 3.2.9 and Python 3.6.8) -
Using django templates to try to display an image
I'm trying to get an image to display on my webpage. I created a static folder in journal and a media folder within that to store my images. I have then attempted to display this image with the following code in my base.html file which i've used at my general template. <img src="{% static "journal/media/Solirius_logo.jpg" %}" alt="Logo" /> But PyCharm is telling me the tag is not closed referencing the start of the url path.Image on webpage -
Python 3.10/Django 3.2.7: No module named 'MySQLdb'
This week I started working home and tried installing my project on my PC but it won't work. I cloned the git repo, installed MySQL Workbench and Server and stuff, installed Visual C++ stuffs and loads of modules from my requirements.txt. But when I try to run ./manage.py migrate it spits out this: $ py manage.py migrate Traceback (most recent call last): File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\db\backends\mysql\base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\lisa-\projects\register\manage.py", line 22, in <module> main() File "C:\Users\lisa-\projects\register\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\lisa-\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\contrib\auth\models.py", line 3, … -
django token authentication not working properly
Hi Everyone i have configure token authentication in my project, when i post username and password on postman token are generating but when i added this token to access my api respose then getting [Authentication credentials were not provided.] models.py from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) settings.py INSTALLED_APPS = [ 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'api.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication' ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework_datatables.renderers.DatatablesRenderer', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework_datatables.filters.DatatablesFilterBackend', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework_datatables.pagination.DatatablesPageNumberPagination', 'PAGE_SIZE': 100, } urls.py from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('login',obtain_auth_token,name="login") ] #api for response views.py class HisaabViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset=WeeklyData.objects.all() serializer_class=HisaabSerializer -
Slurm web interface
i'm working on a project for my company, and i'm trying to do a web interface in order to integrate different tools like Slurm, Zabbix, Nagios, etc... The first thing i'm trying to do is to integrate Slurm to give to a user the possibility to submit jobs, see the resources allocated and other infos. I think the best method to to achive this is program my web interface to dialogate with the RestAPI of Slurm and get all the infos to display and submit jobs with that. What do you think about that? There are other better choices to do that? -
extra select field not returning from django-rest serializer's create() method
Django==3.1.5 djangorestframework==3.12.2 I want to sort with the order_by() method for a dynamically calculated field. This field is "is_active". I added this field in ActivityModelManager class as below. "is_active" field does not appear in the data returned from the serializer's create method. But the data returned from the serializer's update method is coming. managers.py class ActivityModelManager(models.Manager): def get_queryset(self): qs = super().get_queryset() today = datetime.datetime.today().date() qs = qs.extra(select={'is_active': 'start_date <= %s AND %s < finish_date'}, select_params=(today, today)) return qs model.py class ActivityModel(TimestampAbstractModel): name = models.CharField(max_length=255) start_date = models.DateField() finish_date = models.DateField() vacancy = models.PositiveIntegerField(validators=[MinValueValidator(limit_value=1)]) objects = ActivityModelManager() def __str__(self): return self.name serializers.py class ActivitySerializer(serializers.ModelSerializer): is_active = serializers.BooleanField(read_only=True) class Meta: model = ActivityModel fields = [ 'id', 'name', 'start_date', 'finish_date', 'vacancy', 'is_active' ] read_only_fields = [ 'id', 'is_active' ] import datetime from dateutil.relativedelta import relativedelta from my_app.models import ActivityModel from my_app_serializers import ActivitySerializer ############# #creating ############# start_date = datetime.datetime.today.date() finish_date = start_date + relativedelta(months=1) data = { "name" : "Activity name", "start_date" : start_date, "finish_date" : finish_date, "vacancy" : 60 } serializer = ActivitySerializer(data=data) serializer.is_valid() ret_val = serializer.save() ##################################################### #ret_val variable has not contain "is_active" field. ##################################################### ########### #updating ########## instance = ActivityModel.objects.create( name = "Activity Name" start_date = start_date, finish_date = … -
Align Navbar items
I'm having this weird glitch that doesn't align the Navbar items (Navbar preview) I tried fixing it manually by adding margin and padding but I wasn't successful due to my lack of Bootstrap knowledge #cart-icon{ width:25px; display: inline-block; margin-left: 15px; margin-right: 20px; } #cart-total{ display: block; text-align: center; color:#fff; background-color: red; width: 10px; height: 25px; border-radius: 50%; font-size: 14px; } <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'store' %}"> Luffy </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link active" href="#">Store</span></a> </div> </div> <div class="form-inline my-2 my-lg-0 mr-auto"> <a href="#"class="btn btn-warning">Login</a> <a href="{% url 'cart' %}"> <img id="cart-icon" src="https://stepswithcode.s3-us-west-2.amazonaws.com/m1-prt4/6+cart.png"> <p id="cart-total">0</p> </a> </div> </nav> how can I fix this?