Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access to the requested URL within a Django handler404 redirection?
I am sure this has a trivially easy answer but I have spent a couple of hours with Google and Stack Overflow without finding any answer. I am building a Django CMS for a multi-language web site. URLS take the form: https://example.com/xx/subject where x is a two-letter code for a language (en=English, fr=French). For example: https://example.com/en/about-us https://example.com/fr/a-propos I need to be able to access the requested URL from within the handler404 view to provide appropriate content to the visitor. I currently have a working 404 redirect in the Django app: project.urls.py handler404 = 'myapp.views.error404' myapp.views.py def PageView(request, lang, subject): [creates a page with DB content based on lang & subject] def error404(request, *args, **kwargs): return PageView(request,'en','404page',) I would like to know what the requested URL was in order to redirect the visitor to a page in their language. Under this system the 404 page will be a page in the CMS like any other, so it will be editable by the CMS user (I am not using Django templates to create pages). There will be one "404page" entry in the DB for each language. Here is a non-working example of the kind of thing I'm looking for: def error404(request, *args, … -
Django get related info from Many to Many through table
I have something similar to the following model class User(Model): username = CharField(...) class Event(Model): event_name = CharField(...) event_rating = IntegerField users = ManyToManyField(User, through="UserEventAttendence") class UserEventAttendence(Model): user = ForeignKey(User) event = ForeignKey(Event) attended = BooleanField() class EventComments(Model): name = CharField(...) content = CharField(...) event = models.ForeignKey(Event, related_name='eventcomments', on_delete=models.CASCADE) In my view I am trying to get all events, the users for each event, then from this filter out events that the current user is going to. Below is my current query (goes to a serializer afterwards and is then sent as a response) events = models.Event.objects.using(db_to_use).prefetch_related( Prefetch('users', queryset=models.UserProfile.objects.using(db_to_use)) ).prefetch_related( Prefetch('eventcomments', queryset=models.EventComments.objects.using(db_to_use)) ).filter(usereventattendence__user_id=request.user.id) But I need to somehow append the "attended" field from the "UserEventAttendence" model for each event (for the current user), but I don't have any clue how to go about it. -
Django - How do I use UserChangeForm my in web-app?
When I tried to modify the current entry with UserChangeForm in my page, it says "User is already existed". But the I had no problem modifying the entry through the admin portal. model.py class User(AbstractUser): users = ( ('doctor', 'Doctor'), ('patient', 'Patient'), ('assistant', 'Assistant'), ) user_type = models.CharField(choices=users, max_length=9, default='patient') #return the users' name def __str__(self): return self.first_name + " " + self.last_name class Doctor(models.Model): upin = models.AutoField(primary_key=True) #unique physician identification number user = models.OneToOneField(User, on_delete=models.CASCADE) user.user_type = "doctor" specialty = models.CharField(max_length=20) appointments_per_hour = models.IntegerField(null=True) #return the doctors' name def __str__(self): return str(self.user) forms.py class DoctorForm(UserChangeForm): class Meta: model = Doctor fields = ('user','specialty','appointments_per_hour',) -
Reload choices dynamically when using MultipleChoiceFilter
I am trying to construct a MultipleChoiceFilter where the choices are the set of possible dates that exist on a related model (DatedResource). Here is what I am working with so far... resource_date = filters.MultipleChoiceFilter( field_name='dated_resource__date', choices=[ (d, d.strftime('%Y-%m-%d')) for d in sorted(resource_models.DatedResource.objects.all().values_list('date', flat=True).distinct()) ], label="Resource Date" ) When this is displayed in a html view... This works fine at first, however if I create new DatedResource objects with new distinct date values I need to re-launch my webserver in order for them to get picked up as a valid choice in this filter. I believe this is because the choices list is evaluated once when the webserver starts up, not every time my page loads. Is there any way to get around this? Maybe through some creative use of a ModelMultipleChoiceFilter? Thanks! -
How to stop the Django development server on windows
I found here answers how to stop the Django Server on Linux but not on windows. Do I really need to restart my machine ? -
Pass the url view in the forms label. DJango
How to correctly pass the view name in 'label'. My form looks like that. class DocumentationForm(forms.Form): documentation = forms.BooleanField(label='I accept the terms and <a href="{%s}">conditions</a>.' %('app:documentation'), initial=False) def clean_website_rules(self): data = self.cleaned_data['documentation'] if not data: raise forms.ValidationError("Please accept the terms and privacy policy.") else: return data When I click on the link, something like that is created. host:name/data_1/data_2/data_3/documentation/ But how to receive: host:name/documentation/ If I used this in the template, the correct name would look like this {% url 'app:documentation' %}. Any help will be appreciated. -
Share a single connection bewteen django requests
Looking for a reliable way of sharing connection objects in django project, similarly to django database connections. from django.db import connections with connections['default'].cursor() as cursor: cursor.execute(sql, params) Not necessarily with the same API but I need a similar way of acquiring redis connection pools which initializes on django server startup, so I could reuse single connection pool from different parts of the project. Do you have any suggestions or ideas how can I approach this issue ? -
Django nested models in class based views
I'm relatively new to python/django and I'm not sure I'm doing this right Suppose there are 2 different apps projects and items. The url I have in the items app is: path('projects/<slug:project_slug>/items/', ItemListView.as_view()) And the cb-view: class ItemListView(CanViewProjectMixin, ListView): model = Item def get(self, request, *args, **kwargs): self.project = Project.objects.get(slug=kwargs.get('project_slug')) return super(ItemListView, self).get(request, *args, **kwargs) def get_context_data(self, *, object_list=None, **kwargs): context = super(ItemListView, self).get_context_data(**kwargs) context['project'] = self.project return context This seems to work fine in the view, and it is passing the project object to the template via context However, I'm not able to get self.project in the CanViewProjectMixin.dispatch() method. Any help would be appreciated -
expected string or bytes-like object error while save an object
i wrote this code on models.py but in shell when i try to save an object from Question, this error comes up : Traceback (most recent call last): File "", line 1, in File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\base.py", line 718, in save force_update=force_update, update_fields=update_fields) File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\base.py", line 748, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\base.py", line 831, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\base.py", line 869, in _do_insert using=using, raw=raw) File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\query.py", line 1136, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\sql\compiler.py", line 1288, in execute_sql for sql, params in self.as_sql(): File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\sql\compiler.py", line 1241, in as_sql for obj in self.query.objs File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\sql\compiler.py", line 1241, in for obj in self.query.objs File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\sql\compiler.py", line 1240, in [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\sql\compiler.py", line 1182, in prepare_value value = field.get_db_prep_save(value, connection=self.connection) File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\fields__init__.py", line 790, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\fields__init__.py", line 1429, in get_db_prep_value value = self.get_prep_value(value) File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\fields__init__.py", line 1408, in get_prep_value value = super().get_prep_value(value) File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\fields__init__.py", line 1268, in get_prep_value return self.to_python(value) File "H:\virtualEnvs\Django_1\lib\site-packages\django\db\models\fields__init__.py", line 1369, in to_python parsed = parse_datetime(value) File "H:\virtualEnvs\Django_1\lib\site-packages\django\utils\dateparse.py", line 106, in parse_datetime match = datetime_re.match(value) … -
Django MIDDLEWARE problem with RemoteUsers
My settings.py: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend', 'django.contrib.auth.backends.ModelBackend', ] MIDDLEWARE = [ # ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', # ... ] ModelBackend is used by the DRF Browsable API. RemoteUserBackend is used by the frontend app. If a user logs into the Browsable API, the frontend will send both the auth token and the session token. Both credentials are diferent django users. AUTHENTICATION_BACKENDS are suposed to work by order, but AuthenticationMiddleware goes first in MIDDLEWARE , it's mandatory. A session-authenticated user gets wrong data in the frontend app. Django ignores remote user credentials. The user must logout from the browsable API. How can I fix this? -
Django -> dict access template from context_proccesor function
Context_procesor from .models import MdPaginas def fn_mdpaginas(request): mdpaginas = dict() paginas = MdPaginas.objects.all() for pagina in paginas: mdpaginas[pagina.title] = pagina.id print('procesador de paginas ->', mdpaginas) return mdpaginas Print shows 3 dict items upon console. How ever this template code fail: {% for id, titulo in mdpaginas.items %} <p> {{titulo}} hola </p> {% empty %} No hay paginas {% endfor %} HTML shows -> 'No hay paginas' ¿ What´s my error ? ¿ What can I do to use dict ? -
Django modify queryset values before rendering on the template
I have a FormView that sends data to a ListView. In the LisView I get the data with self.request.GET and unsing a qustom filter I get the queryset that I need. Now I need to modify some values in the queryset, but I dont find how. Tried indexing the queriset in the ListView with queriset['name'], or queryset[1], but its tell me that the index is not suported. Tried apply queryset.values_list() and queriset.values() then indexing, but the same result apears. Tried to create a function in the ListView and apply in the template getting 'Could not parse the reminder'. Finally tried to rest the values in the template by doing object.value - request.GET.value but I get an error to. views.py class QuoteListView(ListView): model = SmgQuotesTable def get_queryset(self): r_get = self.request.GET d_get = {'name': None , 'email':None , 'couple': None, 'age': None, 'kids':None , 'salary':None} for value in d_get: d_get[value] = r_get[value] query_filter = Quotes().planSelector(d_get['couple'], d_get['kids'], d_get['age']) queryset = super(QuoteListView, self).get_queryset().filter(composite=query_filter) return queryset def salary(self, x): salary_get = self.request.GET('salary') return x - salary_get smgquotestable_list.html {% for item in object_list %} <div class="table-responsive text-nowrap"></div> <table class="table table-striped"> <thead> <tr> <th scope="col"></th> <th scope="col">SMG01</th> <th scope="col">SMG02</th> <th scope="col">SMG10</th> <th scope="col">SMG20</th> <th scope="col">SMG30</th> <th scope="col">SMG40</th> … -
Updating model's FileField manually in django views
I have a csv file stored in a model's FileField. I want to drop selected columns from the csv file and update the file stored in the Project's FileField. I have successfully retrieved the file from the model and stored it into a Pandas DataFrame. Selected columns are successfully dropped from the dataframe BUT failed to UPDATE the file stored in the Project's FileField. Here is my model: class Project(models.Model): name = models.CharField(max_length=100) description = models.TextField() base_file = models.FileField(upload_to='project-files', default=True) date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Here is the view that suppose to manipulate the file through pandas dataframe: def PreprocessView(request, **kwargs): proj_pk = kwargs.get('pk') project = Project.objects.get(id=proj_pk) df = pd.read_csv(project.base_file) n_cols = df.keys context ={} context['df'] = df context['n_cols'] = n_cols if request.method == 'POST': checked_values = request.POST.getlist(u'predictors') str_check_values = ', '.join(checked_values) df.drop(columns=checked_values, inplace=True) new_df = df.to_csv(project.base_file.name) project.base_file = new_df project.save() messages.success(request, f'{str_check_values} has been successfuly removed!') return render(request, 'projects/preprocess/preprocess.html', context) The following lines returns an error and fail to update the File in the database. new_df = df.to_csv(project.base_file.name) project.base_file = new_df project.save() -
I Got Indentation Error. How to Fix it......?
After running server, it gives error for unexpected indentaion....!!!! What should i do....???? from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author= models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title -
Filter raw query Django Rest Framework Filter
When I want to query and filter: 'RawQuerySet' object has no attribute 'all' views.py class groupdatagercekzamanliveriListView(ListAPIView): query2 = gercekzamanlıveri.objects.raw("""SELECT isyeri_id as id,isyeri_id, CONCAT((ROUND(SUM(net_uretim_miktari)/SUM(teorik_uretim_miktari)::float*100)),'%%') as gtee FROM (SELECT tee_gercekzamanlıveri.id,tee_gercekzamanlıveri.isyeri_id,tee_malzemeler.malzeme as malzeme,tee_gercekzamanlıveri.tarih,tee_gercekzamanlıveri.brut_uretim_suresi,tee_gercekzamanlıveri.net_uretim_miktari,tee_isyerimalzemebilgileri.net_islem_zamani,tee_isyerimalzemebilgileri.satis_fiyati,tee_isyerimalzemebilgileri.uretim_maliyeti, (tee_gercekzamanlıveri.brut_uretim_suresi*60/tee_isyerimalzemebilgileri.net_islem_zamani) as teorik_uretim_miktari, ROUND((tee_gercekzamanlıveri.net_uretim_miktari/(tee_gercekzamanlıveri.brut_uretim_suresi*60/tee_isyerimalzemebilgileri.net_islem_zamani)::float)*100::float) as tee, (tee_isyerimalzemebilgileri.satis_fiyati*tee_gercekzamanlıveri.net_uretim_miktari) as toplam_ciro, (tee_isyerimalzemebilgileri.uretim_maliyeti*tee_gercekzamanlıveri.net_uretim_miktari) as toplam_maliyet, ROUND((ROUND((tee_gercekzamanlıveri.net_uretim_miktari/(tee_gercekzamanlıveri.brut_uretim_suresi*60/tee_isyerimalzemebilgileri.net_islem_zamani)::float)*100::float))*(((tee_isyerimalzemebilgileri.satis_fiyati*tee_gercekzamanlıveri.net_uretim_miktari)-(tee_isyerimalzemebilgileri.uretim_maliyeti*tee_gercekzamanlıveri.net_uretim_miktari))/(tee_isyerimalzemebilgileri.uretim_maliyeti*tee_gercekzamanlıveri.net_uretim_miktari)::float)) as vt FROM tee_gercekzamanlıveri INNER JOIN tee_isyerleri ON tee_gercekzamanlıveri.isyeri_id= tee_isyerleri.id INNER JOIN tee_malzemeler ON tee_gercekzamanlıveri.malzeme_id= tee_malzemeler.id INNER JOIN tee_isyerimalzemebilgileri ON tee_isyerimalzemebilgileri.isyeri_id= tee_gercekzamanlıveri.isyeri_id AND tee_isyerimalzemebilgileri .malzeme_id = tee_gercekzamanlıveri.malzeme_id) as a GROUP BY isyeri_id""") serializer_class = groupdatagercekzamanlıveriserializer queryset = query2 filter_backends = (DjangoFilterBackend,) filter_fields = ('id',) serializer.py class groupdatagercekzamanlıveriserializer(serializers.Serializer): id = serializers.IntegerField() gtee = serializers.CharField() -
How to import excel files in django that has a foreign key?
I am trying to import excel file through django admin(Import-export). I have two tables. Brand master and Item master. I am using Brand Master as a foreign key in Item master. When I upload brand master file, it is uploading. But when I try to import Item master there is a problem Below is the model. from django.db import models class Sales(models.Model): Invoice_Date = models.CharField(max_length = 20, db_column = 'Invoice Date') Sales_Value = models.CharField(max_length = 20, db_column = 'Sales Value') class BrandMaster(models.Model): Line_cd = models.CharField(max_length = 10, db_column = 'Line cd') Ver_name = models.CharField(max_length = 30, db_column = 'Ver name') Brand_man = models.CharField(max_length = 30, db_column = 'Brand man') Exec_HR = models.CharField(max_length = 40, db_column = 'Exec HR') Cat_man = models.CharField(max_length = 20, db_column = 'Cat man') def __str__(self): return self.Line_Code class ItemMaster(models.Model): Brand_Master = models.ForeignKey(BrandMaster, on_delete=models.CASCADE) Line_Code = models.CharField(max_length = 10, db_column = 'Line cd') Item_ID = models.CharField(max_length = 30, db_column = 'Item ID') Item_Name = models.CharField(max_length = 30, db_column = 'Item Name') def __str__(self): return self.Line_Code This is the admin.py file. from django.contrib import admin from .models import Sales,BrandMaster,ItemMaster from import_export import resources from import_export import fields from import_export.admin import ImportExportModelAdmin from import_export.widgets import ForeignKeyWidget class SalesResource(resources.ModelResource): id … -
django request distant database
I'm trying to request, in a django project "FIRST", an existing database for an other django project "SECOND" witch are deployed in two differents machines. I need to get in app 1 the values of an attribute's modele in app5 (as explained below). I've search "how django requests distant database" but i didn't found an answer to my question Thank you, Machine 1 (192.xxx.xx.xx) : ----- project FIRST ------APP1 ------APP2 Machine 2 (192.yyy.yy.yy) : ----- project SECOND ------APP3 ------APP4 ------APP5 -
How Django know which view is assigned to which method?
I have 2 models named Student and course. I'hve created 4 views of CRUD. i am performing CRUD operations, i want to know how CRUD views assigned to each model internally ? (i want to know internal working of views and models) -
Difference between UniqueConstraint vs unique_together - Django 2.2?
I started the new project in Django using version 2.2,which has new constraint unique constraint, Does this same as unique_together or it has any other differences? -
How to login automatically after signup in django customuser?
So I followed a tutorial online about creating a customuser registration/login in django. Now both works fine. when user logs in from login page it uses this link LOGIN_REDIRECT_URL = 'profile'. But for a user that just registered I want it to be logged in automatically and also redirect to suggestion as in the view not to the profile. But I don't know how to login the user from this view. I tried to add to use login() here but I have no idea how to use it here. class SignUp(generic.CreateView): form_class = CustomUserCreationForm template_name = 'signup.html' success_url = reverse_lazy('suggestion') -
how to deploy tensorflow system? tensorflow serving?
I have built a recommender system with tf.keras. I'd like to deploy this to a live environment. One thing I could do is, create a python-based webserver (django) that takes (http) rest request, do the prediction with the trained model and gives back the result as a rest response. I wonder if there's recommended alternative than doing the above? I can guess tensorflow serving might be related to what I'm trying to do, but couldn't tell for sure.. I'm subsclassing tf.keras.models.Model to create my model, and it doesn't support model.save() only model.save_weights .. It might affect my options I guess. -
How to export a PDF from an endpoint in Django Rest Framework
I'm currently setting up a GET request from my endpoint to export a PDF file based on the filters(django_filters) on my ModelViewSet and the PDF's design will based on the template_path provided. And I'm fairly new on using DRF, so I'm new to some things. I've tried using easy_pdf for my ModelViewSet, but it doesn't show on the endpoint's GET request. And also no error was provided in the logs, I assume I'm doing something really wrong on this. This is my Filter class CarrierFilter(django_filters.FilterSet): date_app_rec__gte = DateFilter(field_name='date_app_rec', lookup_expr='gte') date_app_rec__lte = DateFilter(field_name='date_app_rec', lookup_expr='lte') date_sample_rec__gte = DateFilter(field_name='date_sample_rec', lookup_expr='gte') date_sample_rec__lte = DateFilter(field_name='date_sample_rec', lookup_expr='lte') date_of_qca__gte = DateFilter(field_name='date_of_qca', lookup_expr='gte') date_of_qca__lte = DateFilter(field_name='date_of_qca', lookup_expr='lte') date_created__gte = DateFilter(field_name='date_created', lookup_expr='gte') date_created__lte = DateFilter(field_name='date_created', lookup_expr='lte') patient_name = CharFilter(field_name='patient_name', lookup_expr='icontains') class Meta: model = Carrier fields = ('date_app_rec__gte', 'date_app_rec__lte', 'date_sample_rec__gte', 'date_sample_rec__lte', 'date_of_qca__gte', 'date_of_qca__lte', 'date_created__gte', 'date_created__lte', 'patient_name',) And this is my ModelViewSet class CarrierViewSet(XLSXFileMixin, PDFTemplateResponseMixin, ModelViewSet): serializer_class = CarrierSerializer permission_classes = (IsAuthenticated,) parser_classes = (MultiPartParser,) filename = 'carrier-reports.xlsx' pdf_filename = 'carrier-report.pdf' filter_class = (CarrierFilter) filterset_fields = ('patient_name', 'promo_code') search_fields = ('patient_name', 'promo_code', 'insurance_verified_tsg_verification') def get_queryset(self): user = self.request.user position = self.request.user.position if position == 'Manager': queryset = Carrier.objects.filter(manager__name=user) else: queryset = Carrier.objects.filter(agent__name=user) return queryset def get(self, request, format=None): carrier = … -
Django “Performing System Checks” takes a lot of time
I see that this issue appears on SO sometimes. I have a project that is taking too long to start, and performing the python -v manage.py check command I can see that it "halts" on the google-auth package. Any idea on how to make the checks run faster? Tks -
How to update a field in database Django?
I need to update my student's total score for my application but but the problem is that I can not update this value. Models: class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) quizzes = models.ManyToManyField(Quiz, through='TakenQuiz') total_score = models.FloatField(default=0) def __str__(self): return self.user.username class Meta: verbose_name = 'Estudantes' Obs: The tota_score has default value = 0 views: class TakenQuizListView(ListView): model = TakenQuiz context_object_name = 'taken_quizzes' template_name = 'classroom/students/taken_quiz_list.html' def get_queryset(self): queryset = self.request.user.student.taken_quizzes \ .select_related('quiz', 'quiz__subject') \ .order_by('quiz__name') return queryset def get_context_data(self, **kwargs): total_score = self.request.user.student.total_score print(type(total_score)) total_score = TakenQuiz.objects.aggregate(Sum('score')) print(total_score['score__sum']) print("ttt") student = self.request.user.student context = super().get_context_data(**kwargs) context['total_score'] = total_score['score__sum'] return context I can get the full score but I can not update the field in the models. -
type object 'Cart' has no attribute 'objects' in django website
I am trying to learn to make cart in e-commerce website by watching some tutorial. I get an error while running my code although it works fine in the tutorial but in my code, it gives error something like this. I have no idea why I tried to check my code several time but still I am unable to figure out. type object 'Cart' has no attribute 'objects' These are my codes carts/models.py from django.conf import settings from django.db import models from products.models import Product User = settings.AUTH_USER_MODEL # Create your models here. class CartManager(models.Manager): def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated(): user_obj = user_obj return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) object = CartManager() def __str__(self): return str(self.id) carts/view from django.shortcuts import render from .models import Cart # Create your views here. def cart_home(request): cart_id = request.session.get('cart_id', None) qs = Cart.objects.filter(id = cart_id) if qs.count() == 1: cart_obj = qs.first() print('Cart id exists') else: cart_obj = Cart.objects.new(user=request.user) request.session['cart_id'] = cart_obj.id return render(request, "carts/home.html", {})