Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django inheritance avoid to create many html file
i am new in Django. I have task , i have Horoscope website , there is 12 Zodiac signs Aquarius,Aries and etc.... In Aquarius.html are subcategory like Aquarius love , Aquarius finance .... Template is similar, when visitor click love button i want to show love content of Aquarius ( i do not want to copy paste Aquarius.htmland create another love file and then show) how can do this? For example when user open Aquarius i want to show {% for aqua in aquas %} {% if forloop.last %} Aqua Content text{{aqua.body_text}} {% endif %} {% endfor %} When open Aquarius Love (click love button) show Love content {% for Love in Loves %} {% if forloop.last %} love Content text {{aqua.love_body_text}} {% endif %} {% endfor %} how can do this? if else ? -
Django - Assign & limit every logged-in user to create only one instance
How to limit every logged-in user to create only one instance/object from the frontend? here's my model looks like: class MyModel(models.Model): u_name = models.OneToOneField(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE) ... ... my_linkedin = models.URLField(unique=True, blank=True, null=True) my_price = models.CharField(max_length=20, default=0) joined = models.DateTimeField(default=now, editable=False) def __str__(self): return self.my_name def clean(self): model = self.__class__ if model.objects.count() > 0 and \ self.id != model.objects.get().u_name_id: print('hell') raise ValidationError("You can only create 1 profile ") my views: class MyCreateView(LoginRequiredMixin, CreateView): model = MyModel fields = [ 'category', .... .... ] template_name = 'index/form.html' success_url = '/' def form_valid(self, form): form.instance.u_name = self.request.user return super().form_valid(form) And my form: class MyModelForm(forms.ModelForm): class Meta: model = MyProfile fields = '__all__' exclude = ['u_name'] The problem is, that the current code here, they can't assign on every logged-in user. So when I try to login using a different user, The error looks like: get() returned more than one MyProfile -- it returned 3! How can I achieve this? -
Upload very large files directly on NGINX without Django server interaction
I have spent many hours on this but could not find a solution. Problem: I have as simple django server in production and I need to upload files on it using a curl --form command. NGINX latest version 1.16 is working fine on the Ubunut 16 server. Things I tried NGINX upload module (version mismatch)* NGINX upload module's needs a lower version and upon adding the module and making the module, NGINX server fails. I tried installing NGINX from source. The version mismatch occurs. A trick to use client_body_in_file_only to directly upload a file without backend(too many files open)** I followed Nginx PHP Failing with Large File Uploads (Over 6 GB) I can see lots of empty files created in the specified path but at the end it gives 502 bad gateway error. Also, I tried to increase the limit of open files but it is not working either https://medium.com/@cubxi/nginx-too-many-open-files-error-solution-for-ubuntu-b2adaf155dc5#:~:text=If%20you%20run%20an%20Nginx,want%20to%20view%20limits%20on. Can someone point out my mistake or mention a detailed tutorial that handles file uploads in NGINX which can be downloaded using curl? NGINX config location /upload { limit_except POST { deny all; } client_body_temp_path /home/<project folder>/media/uploads; client_body_in_file_only on; client_body_buffer_size 25000M; client_max_body_size 25000M; proxy_pass_request_headers on; #proxy_set_header content-type "text/html"; proxy_set_header Content-Length … -
Django - Two or more Many-to-many relationships based on the same intermediary model
In a medical application using Django, there are both Patient and Medication models (with only "name" fields, for the purpose of this question), where three many-to-many relationships need to be established: allergies: Needs no extra fields, so a simple ManyToManyField would suffice other_medication: Table that refers to medication taken by patients for other medical reasons (would also have a 'dose' column) prescriptions: Table that refers to medication prescribed to patients in our clinic (would also have 'dose' and 'duration' columns) I thought about a few possible solutions. My question is basically which is preferrable: Making two unrelated intermediary models (seems a bad idea since it violates DRY principles) class Prescription(models.Model): medication = models.ForeignKey(Medication, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) dose = models.CharField(max_length=32) class OtherMedication(models.Model): medication = models.ForeignKey(Medication, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) dose = models.CharField(max_length=32) duration_in_days = models.IntegerField() Making an abstract model and inheriting from it, which works around the DRY violation but still seems too verbose (Don't even know if this works in Django) class PatientMedicationRelationship(models.Model): class Meta: abstract = True medication = models.ForeignKey(Medication, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) dose = models.CharField(max_length=32) class Prescription(PatientMedicationRelationship): pass class OtherMedication(PatientMedicationRelationship): duration_in_days = models.IntegerField() Also, would the solution for this problem be different if … -
Django + Svelte styles not working, MIME type ('text/html') is not a supported stylesheet MIME type
I am trying to connect my Django app to a Svelte front-end. I directed my template finder to the build directory of the Svelte folder. I won't be using the template features of Django, will be just using DRF with a Svelte frontend so that functionality I do not need. I just want Django to serve the compiled files. TEMPLATES = [ { ... 'DIRS': [ BASE_DIR / '../frontend/public/' ], ... }, ] Then in my view I can just use: urlpatterns = [ path('', TemplateView.as_view(template_name="index.html")) ] When I open my home view on localhost:8000 it loads the index.html just fine. The only problem is that my styles are not being loaded. This is the folder structure: backend app settings.py frontend public build bundle.js bundle.css index.html global.css As my STATIC_ROOT and STATIC_URL I use this: STATIC_URL = '/build/' STATIC_ROOT = BASE_DIR / '../frontend/public/' This works also fine, if I use python3 manage.py collectstatic I get the admin styles in my build directory and I can access the Django admin completey fine. However, when I try to access my homepage on my development server I get these errors in my console: Refused to apply style from 'http://localhost:8000/global.css' because its MIME type … -
How to create a login and registration form using (username, email, password, age and gender) using postgres database in django?
I don't know much about the Django forms or Django ORM but i need this urgently so i can submit this. I have already connected with postgres SQL and set the URLs. but don't know how to authenticate the user. -
Multiple Primary key while migrating | Django Models
Even i have made only one primary key.I don't know why it says error as multiple primary key when I migrate the changes. class Userinfo(models.Model): ''' User info ''' user_name = models.CharField(max_length=30, unique=True, null=False,primary_key=True) full_name = models.CharField(max_length=50, null=False) user_email = models.EmailField(max_length=254,primary_key=False) college_name = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) profile_img = models.ImageField(upload_to=upload_rename, blank=True) Can some help with this ?? -
Unable to open SQLite database file in Cloud9 IDE for a Django app
I was working on an app that seemed to work fine in the Cloud9 IDE, but when I tried to pip install django-ckeditor, I kept getting a [Errno 28] No space left on device message in the console. When I looked the problem up, I came across a post https://github.com/pypa/pip/issues/5816 in Github covering this same issue where someone was trying to install tensorflow into their Django app. Someone in the thread recommended TMPDIR=/data/vincents/ pip install --cache-dir=/data/vincents/ --build /data/vincents/ tensorflow-gpu in the terminal. I tried this, changing tensorflow-gpu to django-ckeditor because that was the package I was trying to install. Without doing enough research on this, I pasted this into my terminal and still got the same message I did intitally, [Errno 28] No space left on device. This caused a major issue with my database. Now, whenever my Django app is running, if I make any interaction with the database, I get the error unable to open database file . This happens if I try to add a post, delete, etc. Basically any CRUD interaction with SQLite3. Also if I try and logout I get the same issue. [![error message][2]][2] I also get this message in my Cloud9 terminal The … -
Celery Workers not doing all write transactions to database with Django
I am using Django with Celery. My celery worker uses Django and its models to perform database transactions. I have several tasks in my worker and each task makes read/write calls to database multiple times. I am running 6 workers, each with a concurrency of 10 threads. The issue I am facing is that it does all read transactions from database correctly, but it misses doing some write transactions to the database. And those write transactions that it misses are consistent. It always fails to write to the database at the same point, though never raises any exception for it. I have tried putting time.sleep(5) between transactions to give it time but no help. I am starting to think its some kind of connection pooling issue. Does anyone else have any ideas on this or gone through same issue? -
mdbootstrap 5 not showing in Django 2.1.15
I have a simple django project. I want to add material design bootstrap in it. settings.py: STATIC_URL = '/static/' # _______________________________________________________________________ STATIC_ROOT = os.path.join(BASE_DIR, '/assets') # _______________________________________________________________________ STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/static') ] urls.py: from .views import index, core, other urlpatterns = [ path('', index, name='startpage'), path('core/', core, name = 'homepage'), ] views.py: from django.shortcuts import render def index(request): return render(request, 'index.html') def core(request): return render(request, 'base.html') index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <title>Material Design for Bootstrap</title> <!-- MDB icon --> <link rel="icon" href="{% static 'assets/img/mdb-favicon.ico' %}" type="image/x-icon" /> <!-- Font Awesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" /> <!-- Google Fonts Roboto --> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" /> <!-- MDB --> <link rel="stylesheet" href="{% static 'assets/css/mdb.min.css' %}" > <!-- Custom styles --> <style></style> </head> <body> <!-- Start your project here--> <header> <!-- Navbar --> <nav class="navbar navbar-expand-lg navbar-light bg-white"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarExample01" aria-controls="navbarExample01" aria-expanded="false" aria-label="Toggle navigation" > <i class="fas fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarExample01"> <ul class="navbar-nav mr-auto mb-2 mb-lg-0"> <li class="nav-item active"> <a class="nav-link" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> … -
How to send meeting invite on email in django form
I would like to implement a form in django, from where i can send meeting invitation. for that I have created a form where a user can enter sender email , start date and end time. now i want when user click on submit button after entering email and time then an email calendar should sent to sender mail through Django admin panel. enter image description here -
DjangoCMS displays Import Error when creating migrations for Custom User Model
I'm creating a test project to get used to Django CMS, and want to implement a Custom User Model that allows users to use their email instead of a username to login, using a 'users' app. Unfortunately I get this error when I try to makemigrations for users: ImportError: cannot import name 'EMPTY_VALUES' from 'django.forms.fields' (C:\Users\andre.virtualenvs\djangocms2-CqiYHU9a\lib\site-packages\django\forms\fields.py) I'm running the project on Python 3.8.2, Django 3.1.1 and DjangoCMS 3.7.4 My models.py: from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin from django.db import models class MyUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError('Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) is_staff = models.BooleanField( 'staff status', default=False, help_text='Is the user allowed to have access to the admin', ) is_active = models.BooleanField( 'active', default=True, help_text= 'Is the user account currently active', ) USERNAME_FIELD = 'email' objects = MyUserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email My admin.py from django.contrib … -
Can we register models in django to a site which is not admin?
I am learning Django using the tutorial https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django I have a doubt as to whether we can register models created in django to any other site which is not admin? Is it possible? I would want to leave the admin page purely for user related purposes. -
how to perform population in django
What is the django or pythonic way to setup a folder which contains populations that are applied to both the production database and also to any local database that a user can spin up when working on the django project locally? -
Reverse for 'movie_filtered_list' with arguments '('',)' not found. 1 pattern(s) tried: ['cinemahole/(?P<genre_slug>[-a-zA-Z0-9_]+)$']
Here I've been trying to add urls to my genres for filtering movies with specific genres. I am kinda noobie in Django so please tell me where I am doing it wrong. Here is my filles and tracebacks. Views.py here please look into movie_list function. from django.shortcuts import render,get_object_or_404,redirect from .models import Movie from taggit.models import Tag from datetime import date from .forms import WriteMovieForm,SearchForm from django.http import HttpResponse from django.contrib.postgres.search import SearchVector from django.core.paginator import PageNotAnInteger,Paginator, EmptyPage def movie_list(request,genre_slug=None): movies=Movie.movies.all() """ for i in movie: i.save() """ #list View gen=None genres=Tag.objects.all() if genre_slug: gen=get_object_or_404(Tag,slug=genre_slug) movies=movies.filter(genre__in=[gen]) paginator=Paginator(movies,10) page=request.GET.get('page') try: movies=paginator.page(page) except PageNotAnInteger: movies=paginator.page(1) except EmptyPage: movies=paginator.page(paginator.num_pages) #form view form=SearchForm() query=None results=[] if 'query' in request.GET: form=SearchForm(request.GET) if form.is_valid(): query=form.cleaned_data['query'] return search_movie(request,query) context={'page':page,'movie':movies,'form':form,'genre':gen,'genres':genres} return render(request,'Movie/list.html',context) def movie_detail(request,movie): movie=get_object_or_404(Movie,slug=movie) release_date=movie.release today=date.today() if today>release_date: movie.status='Released' movie.save() return render(request,'Movie/detail.html', {'movie':movie}) def write_movie(request): if request.method=='POST': form=WriteMovieForm(request.POST,request.FILES) if form.is_valid(): movie=Movie() movie.title=form.cleaned_data['title'] movie.director=form.cleaned_data['director'] movie.starring=form.cleaned_data['starring'] movie.Plot=form.cleaned_data['plot'] movie.poster=form.cleaned_data['poster'] movie.release=form.cleaned_data['release_date'] genre=form.cleaned_data['genre'] if not Movie.movies.filter(title=movie.title,release=movie.release).exists(): movie.save() for i in genre: movie.genre.add(i) return redirect(movie.get_absolute_url()) else: return HttpResponse('Movie Already exists') return redirect(movie.get_absolute_url()) else: form=WriteMovieForm() return render(request,'Movie/add_movie.html', {'form':form}) def search_movie(request,query): results=Movie.movies.annotate(search= SearchVector('title','director','starring'), ).filter(search=query) return render(request,'Movie/search.html', {'results':results}) models.py from django.db import models from django.utils.text import slugify from django.urls import reverse from datetime import date from … -
How to render data from inline model in django-baton
i am able to render data for Personal Information successfully on my template but i am not able to render data from inline models ie Applicant Current Education and Applicant Personal Experience. Please tell me how to make view function to render data from inline model. Please help me out . listing is the view function for rendering data for Personal information as you can see in picture 1 . Please help me how to render data from inline models -
How are large, varied sets of data for a single user stored?
For organizations which store a large amount of user-specific data, for instance, Instagram stores each user's personal details and then stores an enormous amount of user specific data (Stories, posts, archived data, etc.) How is the database schema made in such a case since all the data cannot be stored on one single table? Also if the project is made in Django with Postgres, how would you make such a database? -
djnago wizzard form - how to redirect, and how to secure the second step?
I have two forms in a row, and I need to send the data from the first to the model in order to save it, then the user has to fill in another form which also sends a part to the model based on the answer. And then his answer in the second form should be combined with the id of the first model. I don't know how to save the data, then redirect to the second step and after sending to make the second step no longer available, it is no longer possible to return to it. views.py: # import models from .models import Profil,Quiz # / import models / # import formulars from .forms import ProfilReg, QuizReg from formtools.wizard.views import SessionWizardView # /import formulars/ # Create your views here. FORMS = [("registrace", ProfilReg), ("quiz", QuizReg)] TEMPLATES = {"registrace": "registrace.html", "quiz": "quiz.html",} class RegWizzard(SessionWizardView): instance = None def get_form_instance(self,step): if self.instance is None: self.instance = Profil() return self.instance def done(self, form_list, **kwargs): project = self.instance project.save() def get_template_names(self): return [TEMPLATES[self.steps.current]] urls.py: from .views import RegWizzard, FORMS from .forms import ProfilReg, QuizReg app_name = 'lide' urlpatterns = [ url('id=(?P<id_uz>\w+)', views.profily, name="profil"), url('registrace', RegWizzard.as_view(FORMS), name="registrace"), url('q', views.quiz, name="quiz"), ] -
How to connect ReactJS via Content Relationship with NOSQL access?
I'm having difficulties to find out how to connect my components throughout api's. I worked before with Microsoft SQL and I, back then, was using foreign key for this stuff, but now I'm really stuck in here. Here are the examples below. Getting all hotels from api endpoint. [ { "id": 51, "name": "Hotel Hollywood", "city": "Sarajevo", "country": "Bosnia & Herzegovina", "image": "http://127.0.0.1:8000/media/images/no-img.jpg", "stars": 4, "date": "2020-09-08 12:22:53", "description": "Hotel Hollywood provides free, secured private parking on site. It also offers 18 conference and meeting rooms.", "price": 1500.0, "likes": 0, "dislikes": 0, "user": [ 1 ], "location": "1.2" } ] Getting all hotel favorites from api endpoint. [ { "id": 5, "name": "Art Hotel", "city": "Belgrade", "country": "Serbia", "image": "/media/images/art.jpg", "stars": 1, "date": "2017-07-04 10:50:12", "description": "Featuring an on-site restaurant and Situated on Belgrade's impressive pedestrian street and shopping zone, Art Hotel's décor is inspired by Italian style. The property offers individually designed, air-conditioned rooms and suites with minibar, free high-speed WiFi, free sauna and hairdryers.\r\n\r\nOffering views of the vibrant Knez Mihailova Street, the elegant Mosaic Restaurant & Bar serves a selection of quality wines and various specialities made from seasonal ingredients, a variety of coffees and homemade desserts, including … -
Django default forms altering
I am trying to change the all the text from the login and registration forms that are generated from Django. Here I want to remove the Username* and Password* text and put them in the input box with different string value. This is how my HTML looks: {% extends 'store/reg.html' %} {% block title %} Login {% endblock %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <form method="post" class="form-signin"> <img class="mb-4" src="/media/logo/log.png"> {% csrf_token %} {{form | crispy}} <button type="submit" class="btn btn-info">Login</button> <p>Don't have an action? Create one <a href="/register">here</a></p> </form> </div> {% endblock %} Similarly I want to change the default text for password validation here Again the Htmlis the same: {% extends 'store/reg.html' %} {% load crispy_forms_tags %} {% block content %} <form method="POST" class="form-group"> <img class="mb-4" src="/media/logo/log.png"> {% csrf_token %} {{form| crispy}} <button type="submit" class="btn btn-info">Sign up</button> </form> {% endblock %} Any suggestions? -
Get database object value in template using Ajax when adding values
I want to fetch database object values. I know one possible solution could be Ajax, but I don't know how to get about it. Below is the code, please help with the implementation. AJAX <script type='text/javascript'> $(document).ready(function () { $(document).on('submit', '#post-form', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "create" %}', data: { title: $('#title').val(), description: $('#description').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (data) { $('#message').html("<h2>Contact Form Submitted!</h2>"); } }); }); }); </script> Views.py class postClass(CreateView): template_name = 'create_post.html' form_class = postForm def create_post(self, request): if request.POST.get('action') == 'post': title = request.POST.get('title') description = request.POST.get('description') Post.objects.create( title=title, description=description, ) Template part <div id='message'>{{ i.title }}</div> Models.py class Post (models.Model): title = models.CharField(max_length=50) description = models.TextField() -
Which is the best way to encode videos into multiple resolutions in django? Should we create a single celery task or to have multiple tasks to encode?
Hey guys Which is the best way to encode videos using ffmpeg into multiple resolutions in django? Should we create a single celery task which encodes the video and save in database or to have multiple tasks to encode video into various resolutions? I am new to all these, so any help regarding the best way is highly appreciated. I have two tasks here to encode into 480 and 1080p..so is it possible to run both in 1 task or the best way is to encode separately? Also how does websites like youtube encode? @task(name= 'task_video_encoding_480p') def task_video_encoding_480p(video_id): logger.info('Video Processing started') try: video = input_file_path = output_file_480p_path = for i in range(1): new_video_480p = subprocess.call([ffmpeg, {process},output_file_480p_path]) if new_video_480p == 0: video.save() logger.info('Video Processing Finished') #video.temp_file.delete() else: logger.info('Proceesing Failed.') # Just for now except: raise ValidationError('Something went wrong!') task 2 @task(name= 'task_video_encoding_1080p') def task_video_encoding_1080p(video_id): logger.info('Video Processing started') try: video = input_file_path = output_file_1080p_path = for i in range(1): new_video_1080p = subprocess.call([ffmpeg, {process},output_file_1080p_path]) if new_video_1080p == 0: video.save() logger.info('Video Processing Finished') video.temp_file.delete() else: logger.info('Proceesing Failed.') # Just for now except: raise ValidationError('Something went wrong!') Thank you. Highly appreciate the help. -
re_path unresolved regex (\d[1,2])
Please let me know why my regular expression cannot be resolved, I just copied and paste from one of the Django book, and tried to passing the parameter re_path(r'^time/plus/(\d[1,2])/$', hours_ahead). Just tried to passing parameter additional hours to current time. http://127.0.0.1:8000/time/plus/2 then I got the page not found (404) error.The current path, time/plus/2, didn't match any of these. I don't understand what is the issue here. please help, thanks. -
Error when installing django on windows using `pip install django`
I get an error when installing django like ERROR: After October 2020 you may experience errors when installing or updating packages. This is because pip will change the way that it resolves dependency conflicts. We recommend you use --use-feature=2020-resolver to test your packages with the new resolver before it becomes the default. drf-yasg 1.17.0 requires six>=1.10.0, but you'll have six 1.9.0 which is incompatible. can anyone help? Thanks in advance -
Django get selected value without Django forms
I have a select form in template which want to get the selected value and update it to item_option field of OrderItem model while running the add to cart function in veiws.py, how can I do it without Django forms? models.py: class product_option(models.Model): option_name = models.CharField(max_length=200) option1 = models.CharField(max_length=200) ... def __str__(self): return self.option_name class Product(models.Model): .... product_option = models.ForeignKey(product_option, on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.product_name def get_add_to_cart_url(self): return reverse("add_to_cart", kwargs={'slug': self.slug}) class OrderItem(models.Model): ... item_option = models.CharField(null=True, max_length=200) template: {% for detail in products %} <a class="btn btn-outline-dark mt-2 mb-3" href="{{ details.get_add_to_cart_url }}"><i class="fas fa-cart-plus mr-2"></i>add to cart</a> <select class="form-control d-inline-block w-50"> <option value="{{ details.product_option.option1 }}">{{ details.product_option.option1 }} </option> <option value="{{ details.product_option.option2 }}">{{ details.product_option.option2 }} </option> .... </select> {% endfor %} views.py def add_to_cart(request, slug): item = get_object_or_404(Product, slug=slug) order_item, created = OrderItem.objects.get_or_create( .... ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): .... order_item.item_option = request.GET.get('value') order_item.save() ... else: .... else: .... return redirect('product_detail', slug=slug)