Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difficulty adding widget to django project
Firstly I apologize for the very basic question but I am currently learning to develop and have read a lot of documentation and searched a lot but still cannot get this working. I'm building a website using Django framework am trying to add the django-bootstrap-datepicker-plus widget. I am having a lot of difficulty figuring out exactly where the different parts of code should go. I have included snippets from my model.py and forms.py files below. The forms work as they are now, but I encounter lots of problems when I try to add the datePicker widget. class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) GENDERS = ( ('M', 'Male'), ('F', 'Female'), ) first_name = models.CharField(max_length=200, default='') surname = models.CharField(max_length=200, default='') gender = models.CharField(max_length=1, choices=GENDERS) class PersonalInformationForm(forms.ModelForm): class Meta: model = PersonalInformation fields = ['first_name', 'surname', 'gender'] Thank you very much and I apologize for the very basic question but I have spent hours trying to figure it out and am just going around in circles. -
Does enabling HTTP/2 in Daphne preclude Daphne's server pushed events feature from working?
The HTTP/2 Support section of the Daphne GitHub page (https://github.com/django/daphne#http2-support) says: Daphne only supports "normal" requests over HTTP/2 at this time; there is not yet support for extended features like Server Push. I plan on using Daphne for its server push feature. Does the above statement imply I should not even try to enable HTTP/2 because it would prevent the server push feature from working at all? -
Apache configuration for serving Django app is not working
I have installed my Django Project on the server, and it is running locally with no problem. I can make migrations and runserver works with no error. I am following this tutorial in order to use Apache to serve the project on Ubuntu, but I am having problems. The first one is where you start Django's development server and allow remote connections (./manage.py runserver 0.0.0.0:8000). When I connect from a remote browser, I get this error: Esta página no funciona 189.172.218.174 envió una respuesta no válida. ERR_INVALID_HTTP_RESPONSE I have also made al configurations to serve the app with Apache, but when a try to connect to the server from a browser, I just get a blank page. No error or anything. This is my 000-default.conf file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last … -
Reverse for 'hire_a_crew' not found. 'hire_a_crew' is not a valid view function or pattern name
I keep on getting a NoReverseMatch at / error when i run my project here is the app level url.py from django.urls import path from . import views from justproduceit_project import settings from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name = 'create' urlpatterns = [ path('equipment_categories/', views.EquipmentCategoriesListView.as_view(), name='equipment_categories'), path('rent_equipment/', views.EquipmentListView.as_view(), name='equipment_home_page'), path('equipment/<slug>/', views.EquipmentDetailView.as_view(), name='equipment_detail'), path('add_to_cart/<slug>/', views.add_to_cart, name='add_to_cart'), path('remove_from_cart/<slug>/', views.remove_from_cart, name='remove_from_cart'), path('checkout/', views.checkout, name='checkout'), path('hire_a_crew/', views.CrewListView.as_view(), name='hire_a_crew'), path('start_a_project/', views.ProjectListView.as_view(), name='start_a_project'), ] here is the settings level urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('pages.urls')), path('learn/', include('learn.urls')), path('create/', include('create.urls', namespace='create')), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] here is the template that is throwing the error <div class="dropdown-menu col-lg-12 text-center" aria-labelledby="dropdownMenuLink"> <h6 class="dropdown-header"><b>Hire a</b></h6> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'hire_a_crew' %}">Crew</a> <a class="dropdown-item" href="#">Director</a> <a class="dropdown-item" href="#">Producer</a> <a class="dropdown-item" href="#">Writer</a> <a class="dropdown-item" href="#">Cinematographer</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'equipment_home_page' %}" role="button">Rent equipment</a> <a class="dropdown-item" href="{% url 'start_a_project' %}" role="button">Start a project</a> </div> -
Multiple arguments from DjangoTemplateLanguage to re_path()
Suppose there's an urlpattern as such : re_path('^(app){3}/$', views.apple, name='apple'), My understanding is that if I want to use a hyperlink of this in templates, I should do as such: <a href="{% url 'apple' 'app' 'app' 'app' %}">apple</a> But what if I wanted to make this pattern? re_path('^(app){100}/$', views.apple, name='apple'), Is there a better way than spamming arguments? -
In forms.ModelForm, Select dropdown not displaying values in queryset() correctly
[models.py] from django.contrib.auth.models import User class Post(models.Model): title = models.CharField() author = models.ForeignKey(User, on_delete= models.CASCADE) [forms.py] from django.contrib.auth.models import User class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','author'] widgets = { 'author': Select(attrs={'style': 'width: 400px;'}), } def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['author'].queryset = User.objects.values_list('first_name') and this is what Select dropdown for Author shows: how do i make it shown this instead: ----- Admin John (PLEASE IGNORE: i'm just adding nonsense here otherwise stackoverflow complains "it looks like your post is mostly code. please add some more details" and won't let me submit. I don't know what else to say so i'm just adding garbage here...) -
How to use Django session variable in models.py
I wanna use the Django session variable on models.py file. How can I do it? -
django-registration invalid activation key error but user account gets activated
When I click on activation link http://127.0.0.1:8000/core/auth/activate/aoisdoaisdoaisdoiaj/ I am taken to a activation_failed page which says - The activation key you provided is invalid. But my account in the database gets activated too. If account is being activated that means activation was successful. Then why would django-registration redirect to failed page. Thanks -
Django models update calculated field according another field
I use Django and I want update many records of my model by using a calculation like in SQL like that : UPDATE table SET amount = pre_tax * 1.2 WHERE amount IS NULL; I want do that with Django ORM. I didn't find any ways to do that. This answer Django - Update model field based on another field don't use bulk update, I need a syntax that allows updating several records. -
Django Multiple form, change second forms content based on 1st form
I need to create a form where, user input from 1st form will change the form 2 content / options. For example consider in 1st form User inputs Number of building Number of floor per building Let's assume the user entered 3 building with 6,7 and 8 floors. In the next form the user has to inputs Sq Ft area per floor per building So Second form needs to have 6 rows/input for building 1, 7 rows/input entry for building 2 and 8 input entry for building 3. Thanks in advance, I am learning Django and apologize if asking a silly question. -
Error - Cannot assign QuerySet. "RfqReply.items" must be a "RequestForQuotationItem" instance. when trying to save the form
also any advise you on how to design the reply model is welcomed. or even how to better structure the views The items are created under one parent through a formset what am trying to archive unit_price, item_total_price are associated with a single item delivery_charges , overall_total, subtotal are associated with all the items models, class RfqFullPrice(models.Model): sender = models.name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="quote_sender")` receiver = models.name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="quote_reciever") requestedquotation = models.ForeignKey(RequestForQuotation, related_name="replyprice_rfq", on_delete=models.CASCADE) subtotal = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', validators=[MinMoneyValidator(0)]) delivery_charges = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', validators=[MinMoneyValidator(0)]) overall_total = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', validators=[MinMoneyValidator(0)]) validity_start_date = models.DateField() validity_end_date = models.DateField() class ReplyItemPrice(models.Model): full_price = models.ForeignKey(RfqFullPrice, on_delete=models.CASCADE, related_name='full_price') the_rfq = models.ForeignKey(RequestForQuotation, on_delete=models.CASCADE) item = models.ForeignKey(RequestForQuotationItem, on_delete=models.CASCADE, related_name="rfq_item") quantity = models.CharField(max_length = 200, help_text='Enter the qauntity') unit_price = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', validators=[MinMoneyValidator(0)]) item_total_price = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', validators=[MinMoneyValidator(0)]) def quote(request, pk): template_name = 'request_quote/send_quote.html' requestedquotation = get_object_or_404(RequestForQuotation, pk=pk) items = RequestForQuotationItem.objects.filter(item=requestedquotation) if request.method == 'GET': full_priceform =QuoteFullPriceForm() item_priceform = QuoteItemPriceForm() elif request.method == 'POST': full_priceform =QuoteFullPriceForm(request.POST, request.FILES) item_priceform = QuoteItemPriceForm(request.POST, request.FILES) if full_priceform.is_valid() and item_priceform.is_valid(): full_priceform = full_priceform.save(commit=False) full_priceform.receiver = requestedquotation.sender full_priceform.sender = request.user full_priceform.requestedquotation = requestedquotation full_priceform.save() for form in item_priceform: form = item_priceform.save(commit=False) form.full_price = full_priceform form.the_rfq = requestedquotation form.item … -
Exception Value: get() returned more than one Conversation -- it returned 2
Ok, so I am getting two conversation objects returned instead of just 1. I believe I am querying correctly, but I still am getting two objects when there only should be one returned. How can I only get the one I need ? I am querying a ManyToMany field, so I may be doing something wrong with that. Error line conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create() views.py/message def message (request, profile_id): if request.method == 'POST': form = MessageForm(request.POST, instance= request.user, sender=request.user, conversation = conversation, message=message, date=date) if form.is_valid(): form.save() return redirect ('dating_app:messages.html') else: conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create() form = MessageForm(instance= request.user, sender=request.user, conversation= conversation, message=message, date=date) context = {'form' : form } return render(request, 'dating_app:messages.html', context) models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You must upload a photo") user = self.model( email=self.normalize_email(email), username = username, description= description, photo= photo, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email,description,photo, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, description=description, photo=photo, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user … -
How do I use conditional statement for different HTML output in Django?
I'd like to use different Bootstrap layouts depending on how many images are found. Currently, I can get a list of images stored in Postgres by doing this: {% for image in post.images %} <div class="d-flex"> <div class="col-md-6 mb-1"> <a href="javascript:void();"><img src="/media/{{ image }}" alt="post-image" class="img-fluid rounded w-100"></a> </div> <div class="col-md-6 row m-0 p-0"> <div class="col-sm-12"> <a href="javascript:void();"><img src="images/page-img/p1.jpg" alt="post-image" class="img-fluid rounded w-100"></a> </div> <div class="col-sm-12 mt-3"> <a href="javascript:void();"><img src="images/page-img/p1.jpg" alt="post-image" class="img-fluid rounded w-100"></a> </div> </div> </div> {% endfor %} In my database, I have images listed listed like: {"/user01/post/Annotation 2020-04-04 132805.png","/user01/post/Annotation 2020-04-05 093855.png","/user01/post/Annotation 2020-04-05 100056.png",/user01/post/default.jpg,/user01/post/Django01.png,/user01/post/Django02.png} I wanted to use an if/then/else statement that would return the amount of images and then only use a specified bootstrap class depending on the image count. post.image.count did not work and I'm wondering how I can get the count of the images. -
How IIS recognize Chinese character in URL
I was developing a django project and deploying it on IIS 7.5. I was using fileField in the model and try to upload files in the django admin. Some of the file names are in Chinese. Before I deploy it on IIS 7.5, if I run the project with python manage.py runserver on the terminal, I can download the uploaded file with Chinese name. But after I deploy it on IIS, it seems like it can not recognized Chinese character. And it gives me an error like this: error pic link Does any one knows what the problem is? I hope I explained the question with enough information. -
includes every template along with its CSS in Django
I'm trying to make every template along with its CSS like Angular or Vue Js so I have done some tries and it's work well here is my shote: <head> <style> {% include "style.css" %} {% block style-custom %}{% endblock %} </style> </head> and for every template: {% block style-custom %} /* some styles */ {% endblock style-custom %} the problem with this way I haven't the ability to change my style like in real CSS it's like a text so I'm asking if there is another way to write my own style inside style tag, like that I will have the ability to change my own styles as I want. -
Which way shall I use foreign key in Django
I have two models, Employee and Withdraw. Which way shall I do the referencing? Like this, as Employee have 0-many withdraws, class Withdraw(models.Model): amount = models.IntegerField(default=0) class Employee(models.Model): name = models.CharField(max_length=200) withdraw = models.ForeignKey(Withdraw, on_delete=models.CASCADE, null=True, blank=True) OR class Withdraw(models.Model): amount = models.IntegerField(default=0) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) class Employee(models.Model): name = models.CharField(max_length=200) What are the pros/cons? Which would you use? -
How to access media files uploaded via a Django form?
I am accepting an image from the user in a form in Django. How do I access the uploaded image to show it in the web browser? This is what I have in settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' This is in my models.py class Hotel(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to="images/") Also, I have added the if settings.DEBUG: urlpatterns +=static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) in urls.py I tried to access the image as def image_view(request): if request.method=='POST': farm = hotelForm(); form = hotelForm(request.POST,request.FILES) if form.is_valid(): form.save() modelff = Hotel(name=request.POST['name'],image = request.FILES['image']) # print(modelff.image.url) return render(request,'djangoform.html',{"form":farm,"uploaded_data_url":modelff.image.url}) else: form = hotelForm() return render(request,'djangoform.html',{"form":form}) And in my template, I accessed the image as <img src="{{uploaded_data_url}}">. But the image does not show up and the console shows image not found. P.S. I have seen How to access media files in django How to access uploaded files in Django? https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development Django : accessing uploaded picture from ImageField But none of them seem to help me. I can't find how do I include the 'images/' in my path. My uploaded_data_url shows /media/Screenshot%202020-04-18%20at%206.39.24%20PM.png while I expect it to show /media/images/Screenshot%202020-04-18%20at%206.39.24%20PM.png Where is the problem? Also, if there can be something similar to How can I get … -
How should I do a survey which shows a brownian motion which depends on the answer?
I want to do a survey in which you write the amount you want to invest, then you see simulations (brownian motions) of different portfolios that you could choose, and then you answer which one you choose. I know how to use Python and Matplotlib, but I don't know how to use Django, which I guess that would be an option. I don't have any web development experience either. What do you thing that would be the easiest way to do it? Django with some webhost? I hope there is an easier solution. Thank you very much -
How do you use the django rest framework serializer to populate a reverse relationship in a m2m mapping?
Here's what I have class Component(models.Model): risks = models.ManyToManyField(Risk) ... class Risk(models.Model): label = models.TextField() ... class RiskSerializer(serializers.HyperlinkedModelSerializer): severity = serializers.SlugRelatedField(queryset=Severity.objects.all(), slug_field='label') class Meta: model = Risk fields = [ 'id', 'label', 'severity', ... ] def create(self, validated_data): print('foo', validated_data) instance = super().create(validated_data) if validated_data.get('component_id'): component = Component.objects.get(id=validated_data.get('component_id')) component.risks.add(instance) return instance What I'm trying to accomplish is I'm trying to create a new Risk using the serializer for an existing component object. Like so: risk = RiskSerializer(data={ 'label': 'foo bar' 'component_id': component.id ... }) risk.is_valid() risk = risk.save() The idea is that if I can pass the component_id then I could override the create method to somehow find and the component object, create it, and then add it to it. But unfortunately because the serializer validates the data and component_id isn't a field that should be there I can't do it this way, the create method won't ever find the component object. What's the correct way to populate Component's risk m2m field? -
Using custom querysets in deep foreignkey Django Filters
I have a model called Users, it derives from a SoftDelete model I've developed. That model has additional querysets defined using models.Manager. This allows me to query the Users model in teh following manner: Users.objects.all() # just the non-deleted objects Users.objects_with_deleted.all() # fetch all, including the deleted. Now let's assume I have a model called Service. It has a manager, expressed with a foreign key to User. manager = models.ForeignKey(User, db_index=True, null=True, on_delete=models.PROTECT) I have an issue running queries like this: services = Service.objects.filter(manager__style="micromanagement") It will return Service objects referencing a soft-deleted User records. It's as if it's not using the default objects queryset I defined for the Users model, prohibiting the fetching of soft-deleted records. Is there a way to instruct filter to use a particular queryset when looking at User records in the deep __style= query? Other than explicitly specifying all the fields that are considered in the custom objects queryset I defined for Users model. It seems counter-intuitive and wasteful, not to mention error-prone and dangerous to re-specify the details of the default objects queryset already override for the Users model into every single query in every single file that tries to deep-filter by it. -
Link to a module member in Spinx
I have a file named models.py which contains a list named CC_TYPES. This exists outside any other class in this file: ... CC_TYPES = ( ('VIS', 'Visa'), ('MAS', 'Master Card'), ('AMX', 'American Express'), ('DIS', 'Discover') ) """Types of credit cards accepted""" class Address(models.Model): """Address information for the 50 US states and Washington DC. **Referenced BY:** :class:`Organization`, :class:`User`""" ... I have CC_TYPES referenced in the Sphinx docs and it is rendering correctly: .. automodule:: eBiz.common.models :members: CC_TYPES What I can't figure out how to do is link from docstring to the CC_TYPES section. I have tried: """Credit Card Type Used. Valid values are listed in `eBiz.common.models.CC_TYPES`_ """ But this gives WARNING: Unknown target name -
In Django, how can I delete object inside template by clicking link?
I made a notification system. When "B" user comments at "A" user's post, notification sends to A. This is my part of my code. models.py from django.db import models from freeboard.models import FreeBoardComment from users.models import CustomUser class Notification(models.Model): TYPE_CHOCIES = ( ("FreeBoardComment", "FreeBoardComment"), ) creator = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, related_name="creator") to = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, related_name="to") notification_type = models.CharField(max_length=50, choices=TYPE_CHOCIES) comment = models.CharField(max_length=1000, blank=True, null=True) post_id = models.IntegerField(null=True) class Meta: ordering = ["-pk"] def __str__(self): return "From: {} - To: {}".format(self.creator, self.to) notification/views.py from django.views.generic import ListView from .models import Notification def create_notification(creator, to, notification_type, comment, post_id): if creator.email != to.email: notification = Notification.objects.create( creator=creator, to=to, notification_type=notification_type, comment=comment, post_id=post_id, ) notification.save() class NotificationView(ListView): model = Notification template_name = "notification/notification.html" freeboard/views.py ... @login_required def comment_write(request, pk): post = get_object_or_404(FreeBoardPost, pk=pk) if request.method == 'POST': form = CreateFreeBoardComment(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comment_writer = request.user comment.post = post comment.save() # 포인트 award_points(request.user, 1) ### NOTIFICATION PART!!!! ### create_notification(request.user, post.author, "FreeBoardComment", comment.comment_text, post.pk) ### NOTIFICATION PART !!! ### return redirect("freeboard_detail", pk=post.id) else: form = CreateFreeBoardComment() return render(request, "bbs/freeboard/free_board_comment.html", {"form": form}) notification.html {% extends "base.html" %} {% block css_file %} <link href="/static/css/notification/notification.css" rel="stylesheet"> {% endblock %} {% block content %} <ul class="list-group"> … -
How to login to a user already created without password?
I have a web page developed in django that uses the django authentication system. To log in to a user, I need their username and password, but I would like to create a login that allows me to enter only by entering the username without the need to use a password, is this possible? Django View class LoginView(SuccessURLAllowedHostsMixin, FormView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = None redirect_field_name = REDIRECT_FIELD_NAME template_name = 'registration/login.html' redirect_authenticated_user = False extra_context = None @method_decorator(sensitive_post_parameters()) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): if self.redirect_authenticated_user and self.request.user.is_authenticated: redirect_to = self.get_success_url() if redirect_to == self.request.path: raise ValueError( "Redirection loop for authenticated user detected. Check that " "your LOGIN_REDIRECT_URL doesn't point to a login page." ) return HttpResponseRedirect(redirect_to) return super().dispatch(request, *args, **kwargs) def get_success_url(self): url = self.get_redirect_url() return url or resolve_url(settings.LOGIN_REDIRECT_URL) def get_redirect_url(self): """Return the user-originating redirect URL if it's safe.""" redirect_to = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name, '') ) url_is_safe = is_safe_url( url=redirect_to, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) return redirect_to if url_is_safe else '' def get_form_class(self): return self.authentication_form or self.form_class def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): """Security check complete. Log the user in.""" auth_login(self.request, form.get_user()) … -
Django 3 . Save Pillow Image to ImageField
I am migrating some code to python 3 and django 3. The image that is being saved is doesn't work, this is the error: Error interpreting JPEG image file (Not a JPEG file: starts with 0x78 0x73) This is the code: import requests from io import StringIO, BytesIO from PIL import Image r = requests.get(img_url) image = Image.open(BytesIO(r.content)) img_file = ContentFile(image.tobytes(), slugify("0_" + card.nombre)) card.image_base.save("0_" + carta_obj.nombre, img_file, save=True) card.image_base is a ImageField. Is there a standard process for this? Pillow + BytesIO + Django? -
'EquipmentOrder' object has no attribute 'equipments'
I am trying to add a new e-commerce feature to my python/django project and i keep on getting an error when i use the add to cart button. I am really frustrated because i have been battling it out for weeks now i really need help. Thanks in advance. here is the EquipmentOrder model class EquipmentOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) equipment = models.ManyToManyField(EquipmentOrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) objects = models.Manager() def __str__(self): return self.user.username here is the add to cart view def add_to_cart(request, slug): equipment = get_object_or_404(models.Equipment, slug=slug) equipment_order_item, created = models.EquipmentOrderItem.objects.get_or_create( equipment=equipment, user=request.user, ordered=False ) equipment_order_qs = models.EquipmentOrder.objects.filter(user=request.user, ordered=False) if equipment_order_qs.exists(): equipment_order = equipment_order_qs[0] # check if equipment order item is in order if equipment_order.equipment.filter(equipment__slug=equipment.slug).exists(): equipment_order_item.quantity += 1 equipment_order_item.save() messages.info(request, "This item quantity was updated.") else: messages.info(request, "This item was added to your cart.") equipment_order.equipments.add(equipment_order_item) else: ordered_date = timezone.now() equipment_order = models.EquipmentOrder.objects.create(user=request.user, ordered_date=ordered_date) equipment_order.equipments.add(equipment_order_item) messages.info(request, "This item was added to your cart.") return redirect("create:equipment_detail", slug=slug)