Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to mock a url path returning response in Django / Python?
I have a function like this: def get_some_data(api_url, **kwargs) # some logic on generating headers # some more logic response = requests.get(api_url, headers, params) return response I need to create a fake/mock "api_url", which, when made request to, would generate a valid response. I understand how to mock the response: def mock_response(data): response = requests.Response() response.status_code = 200 response._content = json.dumps(data) return response But i need to make the test call like this: def test_get_some_data(api_url: some_magic_url_path_that_will_return_mock_response): Any ideas on how to create an url path returning a response within the scope of the test (not using urls.py) would be very much appreciated -
How to Add Certificate Validation django_python3_ldap
I'm trying to integrate AD authentication into my application, but my company requires connections over TLS to AD to trust company CA signed certificates to complete the SSL/TLS handshake. How would I go about adding certificate validation to these settings? # LDAP Connection Settings LDAP_AUTH_URL = ['ldap://xxx.xxx.xxx.xx:636', 'ldap://xxx.xxx.xxx.xx:636'] # Initiate TLS on Connection LDAP_AUTH_USE_TLS = True LDAP_AUTH_TLS_VERSION = ssl.PROTOCOL_TLSv1_2 # LDAP Search BASE for Looking up Users LDAP_AUTH_SEARCH_BASE = 'ou=users,ou=authentication,ou=security,dc=corp,dc=companycom,dc=com' # The LDAP class that represents a user. LDAP_AUTH_OBJECT_CLASS = 'user' # User model fields mapped to the LDAP # attributes that represent them. LDAP_AUTH_USER_FIELDS = { 'username': 'SamAccountName', 'first_name': 'givenName', 'last_name': 'sn', 'email': 'EmailAddress', 'manager': 'manager', 'enabled': 'Enabled' } # A tuple of fields used to uniquely identify a user. LDAP_AUTH_USER_LOOKUP_FIELDS = ('username') # Path to a callable that takes a dict of {model_field_name: value}, # returning a dict of clean model data. # Use this to customize how data loaded from LDAP is saved to the User model. LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" # Path to a callable that takes a user model, a dict of {ldap_field_name: [value]} # a LDAP connection object (to allow further lookups), and saves any additional # user relationships based on the LDAP data. # … -
Default general error message in case of any exception in django
I am developing Restful API using Django. In case of an error instead of raising python default exception or adding try except on every view, is there a way to add a default error message which will be returned? via django settings? via the url's? via a decoretor? thanx in advanced :) Oz -
How to access remote database's tables in Django?
I am accessing the remote database in my Django project as follows: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'remote_db' : { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': 'db_password', 'HOST': '192.*.*.*', 'PORT': '1433', } } For accessing default database table's data, I use the following syntax: from app_name.models import mymodel mymodel.objects.all() My remote database has tables like reports, emplayee_data, etc that are already there and my project has no models defined for these tables. I need to access these tables and I am unsure how to perform this action. remote_db.reports.all() -
How can I use parentheses in Django Slug?
How can I use parentheses in Django project slugs? slug = models.SlugField(max_length=100, unique=True, null=True, allow_unicode=True ) -
Using filter to determine if all via foreign key connected Objects to an Object have property
i am trying to get "All People that possess only books they have read". i have models like: class Person(models.Model): id = Integerfield(primary_key=True) class Book(models.Model): id = Integerfield(primary_key=True) owner = ForeignKey("Person") is_read = BooleanField() Now i am trying to filter with Person.objects.filter(book__is_read=True) but i need something like Person.objects.filter(for_all__book__is_read=True) Is there a way to achive this in Django? -
Django model Queryset negation
I am using Django 3.2. I have written a model manager like this: from django.db.models import QuerySet class FooQueryset(QuerySet): def empty_ones(self): return self.filter(some_field__isnull=True) def nonempty_ones(self): return self.exclude(some_field__isnull=True) All though this example is trivial, I want to keep my code DRY, my logic is more complicated and I want to be able to return the negation of the logic defined in a query function. How may I elegantly do so, using Q expressions? -
Unable to display multiple images on the screen with django
I have just started learning the django framework and I am having issues while displaying the images from the database to the frontend of the website. My database is showing the images uploaded but nothing is being displayed on the page itself. This is my models.py class Post(models.Model): title= models.CharField(max_length=255) author= models.ForeignKey(User,on_delete=models.CASCADE) body = models.TextField() def get_absolute_url(self): return reverse('article-detail', args=(str(self.id))) def __str__(self): return self.title + ' | ' + str(self.author) class Images(models.Model): post= models.ForeignKey(Post,on_delete=models.CASCADE ) image= models.ImageField(null=True, blank=True) This is my views.py class ArticleDetailView(DetailView): model = Post template_name= 'article_details.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['imagelist'] = Post.objects.get(id = self.kwargs['pk']) return context def AddPostView(request): model= Images if request.method == "POST": form= PostForm(request.POST) files = request.FILES.getlist("image") if form.is_valid(): f=form.save(commit=False) f.user=request.user f.save() for i in files: img = Images.objects.create(post=f, image= i) img.save() messages.success(request, "New Blog added") return HttpResponseRedirect("/") else: form= PostForm() imageform= ImageForm() return render (request, "add_post.html",{"form":form,"imageform":imageform}) This is my forms.py from django import forms from .models import Images, Post class PostForm(forms.ModelForm): class Meta: model= Post fields = ('title', 'body','author') widgets = { 'title': forms.TextInput(attrs{'class':'form-control'}), 'body': forms.Textarea(attrs={'class':'form-control'}) } class ImageForm(forms.ModelForm): image= forms.ImageField( label="image", widget= forms.ClearableFileInput(attrs={"multiple":True}), ) class Meta: model= Images fields= ("image",) This is my artice-details.html page {% for pimage in imageslist.image_set.all … -
How to use Django view without response?
I want to make a Django view that handles GET-request to save some data to database (I know there is POST-request, but I want to use GET exactly). But I don't need any response - I don't need reloading the page - it will handled by fetch api in javascript. But if if return no response - the error occurs... Pls advise. -
How to apply changes to ontology saved on SQLite Database?
Everytime I create a new instance on my ontology, something goes wrong If I try to read from the same database again. ps - these are all part of different views on Django This is how I am adding instances to my ontology: # OWLREADY2 try: myworld = World(filename='backup.db', exclusive=False) kiposcrum = myworld.get_ontology(os.path.dirname(__file__) + '/kipo.owl').load() except: print("Error opening ontology") # Sync #-------------------------------------------------------------------------- sync_reasoner() seed = str(time.time()) id_unico = faz_id(seed) try: with kiposcrum: # here I am creating my instance, these are all strings I got from the user kiposcrum[input_classe](input_nome + id_unico) if input_observacao != "": kiposcrum[input_nome + id_unico].Observacao.append(input_observacao) sync_reasoner() status = "OK!" myworld.close() myworld.save() except: print("Mistakes were made!") status = "Error!" input_nome = "Mistakes were made!" input_classe = "Mistakes were made!" finally: print(input_nome + " " + id_unico) print(input_classe) print(status) This is how I am reading stuff from It: # OWLREADY2 try: myworld = World(filename='backup.db', exclusive=False) kiposcrum = myworld.get_ontology(os.path.dirname(__file__) + '/kipo_fialho.owl').load() except: print("Error") sync_reasoner() try: with kiposcrum: num_inst = 0 # gets a list of properties given an instance informed by the user propriedades = kiposcrum[instancia].get_properties() num_prop = len(propriedades) myworld.close() I am 100% able to read from my ontology, but If I try to create an instance and then try … -
KeyError 'first_name'
I am having an KeyError when I clicked to the ADD USER button in the Django Adminastration. I abstracted user and created a new form with abstracted model. Code works when I delete def__init__ in class CustomUserCreationForm but then styling is dissapearing. I added the necessary pictures and codes. Thank you for your help. <body> <div class="container"> <div class="login--wrapper"> <form method="POST" class="form"> {% csrf_token %} <div class="center"> <h1>Kullanıcı Ekle</h1> {% csrf_token %} {% for field in form %} <div class="mb-3"> <label for="exampleInputPassword1" class="from-label">{{field.label}}</label> {{field}} </div> {% endfor %} <button type="submit" class="btn btn-primary">Ekle</button> </div> </div> </div> </div> <body> from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm ,UserChangeForm from django import forms from users.models import DataEbotUser class CustomUserCreationForm(UserCreationForm): class Meta: model = DataEbotUser fields = ['username','first_name','last_name','email','phone','password1','password2'] def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter username...'}) self.fields['first_name'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter First Name...'}) self.fields['last_name'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Last Name ...'}) self.fields['email'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Email...'}) self.fields['phone'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Phone...'}) self.fields['password1'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter password...'}) self.fields['password2'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Confirm password...'}) enter image description here enter image description here enter image description here -
Copying data from a model field to another field without losing data
i wanna copy a data and add it to another field without lose or corrupt data. after that delete old field and continue with new field. Im using postgresql and when i try this connection with fields to copy data i get e.300 and e.307 error as i see on internet this problem cause by wrong foreign key usage and caused by same problem. POST MODEL class Post(models.Model): user = models.ForeignKey('user.CustomUser', verbose_name='Author', on_delete=models.CASCADE, related_name='posts') title = models.CharField(max_length=120) content = models.TextField() image = models.ImageField(null=True, blank=True, upload_to="media/images") publishing_date = models.DateTimeField(verbose_name='Publishing Date', auto_now_add=True) COMMENT MODEL class Comment(models.Model): post = models.ForeignKey('post.Post', related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=200, verbose_name='Name') # user = models.ForeignKey('self.user', related_name='comment', on_delete=models.CASCADE) content = models.TextField(verbose_name='Comment') created_date = models.DateTimeField(auto_now_add=True) I'm currently trying to copy name field to user field and getting e.307 and e.300 post.Comment.user: (fields.E300) Field defines a relation with model 'self.user', which is either not installed, or is abstract. post.Comment.user: (fields.E307) The field post.Comment.user was declared with a lazy reference to 'self.user', but app 'self' isn't installed. Thanks for anyone who try to help. -
Django flash database object
I want to make an app where someone can search for something. When he searches he will get all of the things in the database that start with anything he wrote. Here is the backend code: def home(request): if request.method == 'POST': name = request.POST['name'] search = Team.objects.filter(name__startswith=name).all() if not search: messages.info(request, 'There wasnt') else: #looping all the items that search has for i in search: #flash the object messages.info(request,i) return render(request,'home.html') And the HTML code: {%if messages%} {%for msg in messages%} <div class='searching'> #showing the name and the title of the object <p style='color:white;margin-left:25px;'>{{msg.name}} {{msg.title}}</p> </div> {%endfor%} {%endif%} But when I run it I don't get anything. Also I don't use extra_tags because I want the name and the title appear in the same div. What should I do? Thanks. -
django next variable in url not working correctly
I'm working on a project and there is an odd problem where when the user is logged out and reloads a pre-loaded page, it goes to login page but the next url variable is incorrect. for example if the correct next varibale is like below: http://example.com/login/?next=/exmple/ but the url i'm getting is like this: http://example.com/login/?next=http%3A//host/example/ I should say that 'host' is one of my ALLOWED_HOSTS in settings.py It's very weird because I don't have this problem on debug mode, but only on the actual project that has been launched and is being used by the customer. -
Lightbox gallery navigation images: How to center selected active image
Hello I am using Lightbox gallery on my Django app. When user clicks one of the images, gallery will appear with main selected image, next and prev functional icons and all images on the navigation part. I am trying to center active selected image by floating to the left side of the screen. Image: Code: JS <script type="text/javascript"> function openModal() { document.getElementById("myModal").style.display = "block"; } function closeModal() { document.getElementById("myModal").style.display = "none"; } var slideIndex = 1; showSlides(slideIndex); function plusSlides(n) { showSlides(slideIndex += n); } function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("demo"); if (n > slides.length) {slideIndex = 1} if (n < 1) {slideIndex = slides.length} for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(" active", ""); } slides[slideIndex-1].style.display = "block"; dots[slideIndex-1].className += " active"; } </script> {% endblock %} HTML <div id="myModal" class="modal"> <div class="close-modal-container"> <a href="#" class="btn d-flex align-items-center text-light" onclick="closeModal()" aria-label="{% trans "Close" %}"> <span class="close-icon">{% icon 'CLOSE' 20 version='v2' %}</span> <span class="gr-link2 ml-2">{% trans "Close" %}</span> </a> </div> <div class="body-container"> {% for file in files %} {% if … -
How to create a searchable table from a dict data?
I want to create a search bar for my Django project and user can be able to search reporting_group I'm trying to use django-filters for that. But I'm returning a dict and I cannot use it with django-filters. Is there a way to make a search bar for a dict table? class ProcessTypeGroups(ReportsMixin, ListView): '''Process per Type by Groups''' model = User active_tab = 'reports_group' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) fieldname = 'case_type_value' date_1 = self.request.GET.get('date1') date_2 = self.request.GET.get('date2') cases = Case.objects.filter(date_created__range=[date_1, date_2]).values(fieldname).order_by( fieldname).annotate(the_count=Count(fieldname)) process_types = ProcessType.objects.all() report_group = {} for i in cases: for j in process_types: if str(j) in i["case_type_value"]: report_group[str(j.reporting_group)] = i["the_count"] context['report_group'] = report_group context['date_1'] = date_1 context['date_2'] = date_2 return context The output of the report_group is: {'test': 27, 'Undefined': 44} And my table template: <table class="table table-striped table-condensed"> <thead> <tr> <th>Group</th> <th>Number of Cases</th> </tr> </thead> <tbody> {% for index,key in report_group.items %} <tr> <td> <a href="{% url 'process_groups' date_1 date_2 index %}" style="color: black"> {{ index }} </a> </td> <td>{{ key }}</td> </tr> {% endfor %} </tbody> </table> -
Django ORM: Why is exclude() so slow and how to optimize it?
I have the following 3 queries in my CBV: filtered_content = Article.objects.filter_articles(search_term) filtered_articles = filtered_content.exclude(source__website=TWITTER) filtered_tweets = filtered_content.filter(source__website=TWITTER) Short explanation: I'm querying my database (PostgreSQL) for all article titles that contain the search term. After that, I separate the results into one variable that contains all articles originating from Twitter and the other variable contains all articles originating from all other websites. I have two questions about optimizing these queries. Question 1: Looking at the average time it takes to run these queries, it doesn't make sense to me (filtered_content = less than 0.001 seconds, filtered_articles = 0.2 seconds and filtered_tweets = 0.04 seconds). What is the reason for the exclude() statement (filtered_articles) being so slow? I also tried doing the query in another way, but this was even slower: filtered_content = Article.objects.filter_articles(search_term) filtered_tweets = filtered_content.filter(source__website=TWITTER) filtered_content.exclude(article_id__in=[tweet.article_id for tweet in filtered_tweets]) Question 2: Is there a more elegant way to solve this problem / is there a way to do it in less than 3 separate queries? More specifically, using the Django ORM, is there a way to do a query where all excluded() objects are stored in one variable while all non-excluded objects are stored in another? -
RSA key format is not supported for python that saved in djagno
When users signup to my application, i add new private key and public to every user profile. import Crypto from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 from Crypto.Cipher import PKCS1_OAEP from Crypto import Random recipient = get_object_or_404(User, email=request.POST.get('email')) random = Random.new().read private_key = RSA.generate(1024, random) public_key = private_key.publickey() recipient.private_key = private_key.exportKey('PEM') recipient.public_key = public_key.exportKey('PEM') recipient.save() and then I retrieve the public key to encrypt a message for the user from a background process like this. user = User.objects.get(id=xyz) pvt_key = RSA.importKey(user.private_key) and it fires me these error: ValueErro RSA key format is not supported in database, the public key was saved like this way: b'-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDxcmh0/JQ+2WrpP/1PuSotY7+B\nghEzIjVrqN+rLwSrgzowKIU8Ch3sUMynE2XNgpN6jMiv/Jjb0odptuWwSoZg/NYR\necIr0eLuYIN1R3zic7OwCy86DcML/bNAer89NEk5XHmC5goRZJFn8B+nPyeaQ4Uw\n7JXqmMcCCYflpr9X/QIDAQAB\n-----END PUBLIC KEY-----' Can anyone tell me what's wrong there? how can I solve this problem? -
How to refresh single div includes server logic (Django)?
I have a <div> dynamically rendered with own logic by Django on server side. I use js with fetch() method to make a get request - which updates a database (likes on posts). Then I just wish to refresh <div> that displays the like using server Django logic so that the like displayed properly. I want the logic proceeds on server side - so I need only to refresh part of code (<div>) from the page (Django template). Is it possible? -
CITextField in admin is displayed as text area, not as one line
I'm using python 3.9 with django 4.1 I'm just starting to play with it, I want to use CITextField from Postgresql so i imported it from django.contrib.postgres.fields, it works fine but that admin displays it as TextArea, which means it's not a one-liner input text, it's a all box of text to enter even if i configured a max length of 100 characters. how can I correct that? as an example to show the problem I created a Country model with name_en which is a CharField and name_fr and name_he which are CITextField, all of them are set to max length of 100 characters: class Country(models.Model): class Meta: verbose_name_plural = "Countries" name_en = models.CharField(unique=True, verbose_name="English Country Name", max_length=100) name_fr = CITextField(unique=True, verbose_name="French Country Name", max_length=100) name_he = CITextField(unique=True, verbose_name="Hebrew Country Name", max_length=100) when i browse it on the admin page this is the result: what can I do to resolve it ? thanks -
SSL Cert Verification Error hostname 'x.x.x' doesn't match either of '*exmple.com',
I'm working with many APIs, I send 200,000 requests per day and sometimes I get this error and don't know why: HTTPSConnectionPool(host='x.x.x', port=443): Max retries exceeded with url: /api/x/x/x/x (Caused by SSLError(SSLCertVerificationError("hostname 'api.exmple.com' doesn't match either of '.azureedge.net', '.media.microsoftstream.com', '.origin.mediaservices.windows.net', '.streaming.mediaservices.windows.net'"))) When I was searching for the cause of this problem, I found many responses like you should change Verify =False and like you should add (ssl.match_hostname = lambda cert, hostname: True) But I am really not satisfied with this response because most of the requests are working fine. if 'Content-Type' in header and header['Content-Type'] == 'application/json': if username and password: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout,auth=(username, password),verify=True) else: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout,verify=True) Please help me and thanks -
Annotate queryset with filtered related querysets which should be annotated as well
class A(models.Model): name = models.CharField() class B(models.Model): name = models.CharField() class C(models.Model): name = models.CharField() class D(models.Model): a = models.ForeignKey(A, related_name='set_of_a') b = models.ForeignKey(B, related_name='set_of_d') set_of_c = models.ManyToManyField(C, related_name='set_of_d') I want to get a queryset that should replace the following function (may be pseudocode in some places): def get_queryset(name, list_of_d): result = list(A.objects.filter(name__icontains=name)) for a in result: a.map_b_to_list_of_d = {} # annotation for b in B.objects.filter(set_of_d__set_of_c__intersects_with=set_of_c): a.map_b_to_list_of_d.setdefault(c, []) += list(b.set_of_d.filter(a__name__icontains=name, set_of_c__intersects_with=set_of_c)) return result -
Understanding how the data handling works in production
I do not really understand how the database works when using in production. My stack: Django Heroku AWS S3 PostgresSQL on Heroku Users can generate some images on my app. The images are saved to AWS S3, and in some feature I want to retrieve the last generated image. This below is my model where the images are saved in. models.py: class imgUploadModel(models.Model): auto_increment_id = models.AutoField(primary_key=True, default=True) image = models.ImageField(null=True, blank=True, upload_to="images/") And here the view where the images is taken again and handled in some features. view.py: imgname = imgUploadModel.objects.all().last().image As you can see I use .last() to get to the latest images which was generated. Now to my questions: In production, could it be that one user sees another users images? Or how does the Dynos (from heroku) separate the sessions? Since the AWS S3 bucket is just a memory storage without dividing it by users, I assume that one user can see other users images. Especially then, when user A creates an Img, and user B clicks on 'latest image'. If it is so, how can I create Dynos or Buckets or anything else to prevent this behaviour. I just do not really understand it from a … -
How do I solve django.db.utils.IntegrityError: UNIQUE constraint failed?
How do I solve django.db.utils.IntegrityError: UNIQUE constraint failed? error code is django.db.utils.IntegrityError: UNIQUE constraint failed: Movies_comment.user_id, Movies_comment.tv_or_movie_id. This error occurs Comment(comment=form.cleaned_data["comment"],user=request.user,stars=form.cleaned_data["stars"],tv_or_movie=tv_or_movie_object).save() views.py def view_tv_and_movie_detail(request, type_movie_or_tv, id): tv_or_movie_object, _ = TVAndMovie.objects.get_or_create(tmdb_id=id, judge_tv_or_movie=type_movie_or_tv) detail_tv_or_movie = TvAndMovieDetailhelp(request, tv_or_movie_object, 3) mycomment_obj = detail_tv_or_movie.get_user_post_comment_for_tv_or_movie() if request.method == "POST": if request.POST.get("action") == "delete": mycomment_obj.delete() return redirect("view_tv_and_movie_detail", type=type_movie_or_tv, id=id) else: form = CommentCreateForm(request.POST, instance=mycomment_obj) if form.is_valid() and request.POST.get("action") == "update": form.save() return redirect("view_tv_and_movie_detail", type=type_movie_or_tv, id=id) elif form.is_valid() and request.POST.get("action") == "create": Comment( comment=form.cleaned_data["comment"], user=request.user, stars=form.cleaned_data["stars"], tv_or_movie=tv_or_movie_object, ).save() return redirect("view_tv_and_movie_detail", type=type_movie_or_tv, id=id) else: form = CommentCreateForm(instance=mycomment_obj) data = detail_tv_or_movie.get_object_tv_or_movie_data() recommendations = detail_tv_or_movie.get_recommendations_tmdb_data() pages = detail_tv_or_movie.get_page_comment() average = tv_or_movie_object.average_stars() context = { "data": data, "recommendations": recommendations, "type": "movie", "mycomment": mycomment_obj, "average": average, "form": form, "pages": pages } return render(request, "Movie/movie_detail.html", context) models.py class TVAndMovie(models.Model): tmdb_id = models.CharField( validators=[alphanumeric], max_length=9999 ) judge_tv_or_movie = models.CharField( blank=False, null=False, default="movie", max_length=20 ) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], ) def get_judge_tv_or_movie(self) -> str: return self.judge_tv_or_movie def get_comments(self) -> object: return Comment.objects.prefetch_related("tv_or_movie").filter( tv_or_movie_id=self.id ) def average_stars(self) -> float: comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = round( sum([comment.stars for comment in comments]) / n_comments, 3 ) else: self.stars = 0 self.save() return self.stars class Comment(models.Model): comment = models.TextField(max_length=1000) stars = … -
add if does not already exist
Hello every one I'm trying to write a View Set API, that let you add course obj to your favorite list,but before adding check it if user added course already don't let user add again and if user didn't add so let user add it to the list, but I don't have any idea how can I do it with View set my view class AddtoMyCoursesView(viewsets.ModelViewSet): serializer_class = MyCoursesListSerializer def get_queryset(self, *args, **kwargs): pk = self.request.POST.get('pk') course = get_object_or_404(Courses, id=pk) print(course) course_list, _ = MyCoursesList.objects.filter(courses=course).exist() print(course_list) course_list.courses.add(course_list) My model is class MyCoursesList(models.Model): user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, blank=True) courses = models.ForeignKey(Courses, on_delete=models.CASCADE, blank=True,related_name='my_courses') added_date = models.DateTimeField(auto_now_add=True) teacher = models.ForeignKey(Teacher, on_delete=models.DO_NOTHING, default=1) So what should I do to my code??