Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to make API request
I'm trying to test an API from django app to ensure it is working but I'm totally lost on how to make the API request. I have spent several days trying to figure it out myself but it is obvious that I need help because I keep HAVING ERROR such as TypeError: list indices must be integers or slices, not str. It is an API to create order of selected item. Here is the code: views.py def create_order(request): user = request.user data = request.data orderItems = data['orderItems'] if orderItems and len(orderItems) == 0: return Response({'detail': 'Order item was not provided'}, status=status.HTTP_400_BAD_REQUEST) else: # (1) Create order order = Order.objects.create( user=user, paymentMethod=data['paymentMethod'], #totalPrice=data['totalPrice'] ) # (2) Create shipping address shipping = ShippingAddress.objects.create( order=order, address=data['shippingAddress']['address'], city=data['shippingAddress']['city'], postalCode=data['shippingAddress']['postalCode'], country=data['shippingAddress']['country'], ) # (3) Create order items adn set order to orderItem relationship for i in orderItems: product = Product.objects.get(id=i['product']) item = OrderItem.objects.create( product=product, order=order, name=product.name, qty=i['qty'], price=i['price'], image=product.image.url, ) # (4) Update stock product.countInStock -= item.qty product.save() serializer = OrderSerializer(order, many=False) return Response(serializer.data) How do I represent the Above django view.py in json format to test. Where the issue I'm having is that diffent steps are involved in the view.py file above. Here is … -
Docker container Django not connecting to postgresql
I am having trouble starting up the django app. It seems to freeze when it prints out "System check identified 6 issues (0 silenced)." I believe this is because django is not connected to the postgresql database. I am really unsure of what the problem could be because it was working fine a year ago, and when I am starting it up now it is broken. Here is the output for postgresql from the docker container log /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/* 2022-06-13 03:35:26.151 UTC [48] LOG: received fast shutdown request waiting for server to shut down....2022-06-13 03:35:26.155 UTC [48] LOG: aborting any active transactions 2022-06-13 03:35:26.156 UTC [48] LOG: background worker "logical replication launcher" (PID 55) exited with exit code 1 2022-06-13 03:35:26.156 UTC [50] LOG: shutting down 2022-06-13 03:35:26.204 UTC [48] LOG: database system is shut down done server stopped PostgreSQL init process complete; ready for start up. initdb: warning: enabling "trust" authentication for local connections You can change this by editing pg_hba.conf or using the option -A, or --auth-local and --auth-host, the next time you run initdb. 2022-06-13 03:35:26.273 UTC [1] LOG: starting PostgreSQL 14.3 (Debian 14.3-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit 2022-06-13 03:35:26.273 … -
How to style model form in django with CSS?
I have been using simple forms in Django since I started with python and now I've switched over to model forms, right now I'm wondering how to style the form. I tried to use the widgets code but it is behaving a little funny, If I understand correctly the widgets are to style the form itself (such as input fields) and I can use regular html/css styling on any other elements I have? My desired Is this correct? Here is my code incase there are errors: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static 'css/tripadd.css' %}"> <title>Document</title> </head> <body> <!-- <div class="form-container"> <h4>Add a Trip</h4> <form action="/createTrip" method="post" class="reg-form"> {% csrf_token %} <p><input class="field" type="text" name="city" placeholder="City" id=""></p> <p><input class="field" type="text" name="country" placeholder="Country" id=""></p> <p><textarea name="description" id="" cols="30" rows="10"></textarea></p> <p><input class="field" type="file" name="photo" placeholder="Photo" id=""></p> <input class="form-btn" type="submit" value="submit"> </form> </div> --> {% block content %} <div class="trip-form"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <button type="submit">submit</button> </form> </div> {% endblock %} </body> </html> @import url('https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800,900&display=swap'); * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body{ display: flex; justify-content: center; align-items: center; } … -
Python Django Admin editable field
Is there any way to edit a field in models.py page by entering to admin page without put that field in list_diplay=[] ? -
How do I specify the Django view action decorator for an endpoint with multiple parameters?
For the view and endpoint below with multiple parameters, how should url_path be specified for the action decorator? urls.py: router.register('utils', views.TableColumnViewSet, basename='TableColumn') views.py: @action(detail=False, url_path=r'???') def table_meta(self, request, catalog=None, schema=None, table=None) -
CSS Not Showing Up in Django with NGINX and uWSGI
This is my first real Django project and I am trying to configure it for production using NGINX and uWSGI. It is running on a Digital Ocean Ubuntu server. Everything is set up and working besides serving static CSS files. The strange thing about this is that its serving static images and JavaScript files fine, the only thing that isn't being served is the CSS. This is what my site configuration file for NGINX looks like ('nebula' is the Ubuntu User and the name of the Django project): # configuration of the server server { server_name example.com www.example.com; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/nebula/nebula/media; } location /static { alias /home/nebula/nebula/assets; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/nebula/nebula/uwsgi_params; } } This is what my Settings.py file looks like: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/assets/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') STATIC_ROOT = os.path.join(BASE_DIR, "assets/") STATICFILES_DIRS = ( os.path.join(BASE_DIR,'media/'),) This is what my base directory looks like (assets and static are the same, I duplicated it in an attempt to solve the issue): assets demo.py media nebula.sock static … -
Should I use Comand Prompt or Vs Code terminal for installing modules, running projects ...etc?
I've seen many videos using Comand Prompt to start with a project. Why they use it when you can do it in thier respective IDE's terminal ? -
Django models exclude objects which in self referencing many to many relationship
So in short I have this model: class Post(SoftDeleteModel, TimeStampedModel, models.Model): title = models.CharField(max_length=200) body = models.TextField() image = models.ImageField(upload_to="post_images", blank=True) owner = models.ForeignKey(to=get_user_model(), on_delete=models.CASCADE) comments = models.ManyToManyField(to="self", symmetrical=False, blank=True) having each comment as a post of itself, so comments could have comments and so on, And I want to declare a static method that returns posts only such that they are not in the second column (to column) anywhere in the new auto-generated table from the ManyToMany field, like so: @staticmethod def get_posts_only(): return Post.objects.exclude() what should I exclude or if there is a way with the filter method also. Edit: I got this info about ManyToMany Field from the Django website If the ManyToManyField points from and to the same model, the following fields are generated: id: the primary key of the relation. from_id: the id of the instance which points at the model (i.e. the source instance). to_id: the id of the instance to which the relationship points (i.e. the target model instance). https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ManyToManyField:~:text=If%20the%20ManyToManyField,target%20model%20instance). -
create urls like Instagram posts or youtube video
I'm building a social network and I're going to create my own urls at random the question that has been on my mind for a long time is how to create urls like Instagram posts like Django like the following: https://www.instagram.com/p/CeqcZdeoNaP/ or https://www.youtube.com/watch?v=MhRaaU9-Jg4 My problem is that on the one hand these urls have to be unique and on the other hand it does not make sense that on a large scale when the number of uploaded posts by the user is more than 100,000 I set unique = True Because the performance of the database decreases Another point is the use of uuids, which solves this problem of uniqueness to a large extent, but the strings produced by uuid are very long, and if I shorten these strings and reduce the number of letters in the string, there is a possibility of a collision. And that several identical strings are produced I wanted to know if there is a solution to this issue that generated urls are both short and unique while maintaining database performance Thank you for your time 💙 -
Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x000001D4CBCD96A0>": "Album.owner" must be a "User" instance
I don't know why I have this error, I didn't have it befor, I'm sure that I'm logged in before trying call the api, please find below the code : views.py class AlbumCreate(generics.CreateAPIView): serializer_class = AlbumsSerializer def perform_create(self, serializer): owner2 = self.request.user serializer.save(owner=owner2) class AlbumList(generics.ListAPIView): permission_classes = [IsAuthenticated] queryset = Album.objects.all() serializer_class = AlbumsSerializer class AlbumDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Album.objects.all() serializer_class = AlbumsSerializer Serializer class AlbumsSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField(read_only=True) class Meta: model = Album fields = "__all__" models def upload_path(instance, filname): return '/'.join(['covers', str(instance.title), filname]) class Album(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) cover = models.IntegerField(default=0) photos_number = models.IntegerField(default=0) image = models.ImageField(blank=True, null=True, upload_to=upload_path) def __str__(self): return self.title -
Django Email sending, Rich textbox image triggers email function
I created a Rich Textbox field for emails. Over there I am setting up Some text and inserting a picture. At the email_template.html I added another image, right after the rich textbox field that triggers a link, to see if the mail was opened. The problem is that the image that I insert in the email body triggers the link as well, even if the email has not been opened. I wonder if anyone is stumbled over this problem and how it could be solved? It looks like it triggers because the image is a link as well, so maybe there is an option to load all content only when email is opened? Any thoughts would be helpful. The mail template (email_template.html) : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <meta http-equiv="X-UA-Compatible" content="ie=edge"/> <title>Email Trace</title> </head> <body> <div class="container"> {{ content | safe }} {# Rich textbox is here #} <img src="{{ request.get_host }}/campaigns/email/tr-{{ key }}.png" width="0" height="0" /> </div> </body> </html> The function which triggers img is: def email_seen(request,key): Emails.objects.filter(key=key,email_open=False).update( email_open=True,email_open_times_counter=1,email_open_timestamp=datetime.datetime.now() ) print('Email is opened') with open(os.path.dirname(os.path.abspath(__file__))+"/res/1x1.png","rb") as f: return HttpResponse(f.read(),content_type="image/png") -
Style issue from datatables.net
When I use this database from datatables.net the two buttons of table isn't styling. The next page and previous page buttons. In default it shouldn't be like that. How can I change their style? Here is my html: <h1>MyTable</h1> <table class="table" border=1 id="mydatatablem"> <thead> <tr> <th>Full Name</th> <th>Company</th> <th>Email</th> <th>Phone Number</th> <th>Note</th> </tr> </thead> <tbody> {% for x in x_list %} <tr> <td>{{x.full_name}}</td> <td>{{x.company}}</td> <td>{{x.email}}</td> <td>{{x.phone_number}}</td> <td>{{x.note}}</td> </tr> {% endfor %} </tbody> </table> </div> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src='https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js'></script> <script> $(document).ready(function () { $('#mydatatablem').DataTable(); }); </script> And this is how it looks in the site: enter image description here -
Django Admin is using the wrong UserManager
I have created a custom user class: class User(AbstractUser): objects = UserDashManager() custom_field = models.CharField(max_length=84) And a UserManager to populate that field at creation: class UserDashManager(UserManager): def create_user(self, username, email, password, **extra_fields): extra_fields.setdefault('custom_field', 'custom field value') extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(username, email, password, **extra_fields) I have registered User in admin.py: class CustomAdmin(UserAdmin): model = User list_display = ['username', 'email', 'first_name', 'last_name','is_staff','custom_field'] # Register your models here admin.site.register(User, CustomAdmin) But if I use the admin page http://127.0.0.1:8000/admin/my_app/user/add/ then the user's custom field is blank. I have done the migration, so the field is in the data base. If I create the user in the django shell then the field gets populated, just not from the admin page. Is there something else I need to register? Do I need to create a custom form? How can I get the admin site to use the correct UserManager? -
What could be causing an if statement in a Django template to not change anything?
I am trying to display a message once the user presses the Close Listing on my webpage. Currently, nothing happens to the webpage when the button is clicked. How could I fix this and what is wrong? part of views.py #close listing code if sellar == request.user: closeListingButton = True else: closeListingButton = False closeListing = '' try: has_closed = get_list_or_404(CloseListing, Q( user=request.user) & Q(listings=listing)) except: has_closed = False if has_closed: closeListing = False else: closeListing = True #what happens if listing is closed if closeListing == True: closeListingButton = False has_watchlists.delete() winner = max_bid.user return render(request, "auctions/listing.html",{ "auction_listing": listing, "comments": comment_obj, "bids": bid_obj, "closeListingButton": closeListingButton, "closeListing": closeListing, "closedMessage": "This listing is closed.", "winner": winner }) else: return redirect('listing', id=id) part of listing.html <!--close listing code--> {% if closeListing == True %} <div>{{ closedMessage }} <br> {{ winner }} has won the auction! </div> {% endif %} -
News Feed hidden from users who aren't administrators
On my social media platform, the news feed (called post_list) seems to be hidden from any user that isn't an admin. Even when text is entered into the box and 'post' is pressed, the page refreshes but the text box isn't emptied and no posts appear belowhand. If I log in as an admin, the feed appears immediately and so do all the posts that I just posted from the non-admin account that didn't appear on the non-admin account. As shown here. I have just recently added the ability to share posts, so maybe that has influenced this issue in some manner. (The news feed) post_list.html: > {% extends 'landing/base.html' %} {% load crispy_forms_tags %} > > {% block content %} <div class="container"> > <div class="row justify-content-center mt-3"> > <div class="col-md-5 col-sm-12 border-bottom"> > <h5>Create a Post</h5> > </div> > </div> > > <div class="row justify-content-center mt-3"> > <div class="col-md-5 col-sm-12 border-bottom"> > <form method="POST" enctype="multipart/form-data"> > {% csrf_token %} > {{ form | crispy }} > <div class="d-grid gap-2"> > <button class="btn btn-light" style="background-color: #CC64C3; mt-3 mb-5">Post</button> > </div> > </form> > </div> > </div> > > {% for post in post_list %} > <div class="row justify-content-center mt-3"> > … -
Is it possible to deliver django toast messages via frontend
Tryna achieve sending notifications through Javascript logic instead of Django views, I want to replace alert() in this Javascript function with Django contrib messages(toasts). Something that would look like this in views messages.success(request, f"test successful") Is it possible to achieve the same thing with javascript? js function TestBtn(id) { alert("test successful"); } html <a onclick="TestBtn('btn');return false;"></a> -
How to get the value of or Parse HTML dropdown selected:option text as python variable in views.py in Django?
I have a 3 way dropdown list generated from 3 different tables linked via foreign keys. model.py is a follows #################################################################################### class State(models.Model): state_name = models.CharField(max_length=50, unique=True) state_id = models.PositiveIntegerField(unique=True, validators=[MinValueValidator(1), MaxValueValidator(100)]) class Meta: db_table = 'State_Names' def __str__(self): return self.state_name #################################################################################### class District(models.Model): state_name = models.ForeignKey(State, on_delete=models.CASCADE) state_id = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)]) district_name = models.CharField(max_length=50, unique=True) district_id = models.PositiveIntegerField(unique=True, validators=[MinValueValidator(1), MaxValueValidator(1000)]) class Meta: db_table = 'District_Names' def __str__(self): return self.district_name #################################################################################### class Block(models.Model): state_name = models.CharField(max_length=50) state_id = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)]) district_name = models.ForeignKey(District, on_delete=models.CASCADE) district_id = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(1000)]) block_name = models.CharField(max_length=50) block_id = models.PositiveIntegerField(unique=True, validators=[MinValueValidator(1), MaxValueValidator(8000)]) class Meta: db_table = 'Block_Names' def __str__(self): return self.block_name views.py is as def get_state_district_and_block_string(request): if request.method == "POST": state_name_is=request.POST.get('state_dropdown') print("state_name_is", state_name_is) district_name_is=request.POST.get('district_dropdown') block_name_is=request.POST.get('block_dropdown') return render(request, 'index.html') Dropdown.html is as <div class="form-group"> <label for="state_dropdown">Select State</label> <select class="form-control" id="state_dropdown" name="state_dropdown" aria-label="..."> <option selected disabled="true" class="col-md-12 school-options-dropdown text-center"> --- Select State --- </option> {% for state in stateDetailsInDropdown %} <option class="col-md-12 school-options-dropdown text-center" value="{{state.state_name}}">{{state.state_name}} </option> {% endfor %} </select> </div> <div class="form-group"> <label for="district_dropdown">Select District</label> <select class="form-control" id="district_dropdown" name="district_dropdown" aria-label="..."> <option selected disabled="true" class="col-md-12 school-options-dropdown text-center"> --- Select District --- </option> {% for district in DistrictDetailsInDropdown %} <option class="col-md-12 school-options-dropdown text-center" value="{{district.state_name}}">{{district.district_name}} </option> {% endfor %} </select> … -
BadHeaderError("Header values can't contain newlines (got %r)" % value) in drf_social_oauth2
Describe the bug I got the access_token from google which I'm supposed to use to authenticate users. Everything works fine when the user is authenticating for the first time. But when the user logs out and tries to login again, it gives this wired error. This never happened when I was using the old gapi for login. I am currently using the new recommended GSI google provided. To Reproduce Steps to reproduce the behavior: Go to Google playground to get an access token Send the details to /auth/convert-token endpoint and make sure the user is registered in the database. Try sending the same credentials to the same endpoint. NB: it doesn't matter whether it's a new access_token. as long as it belongs to the same user, the error will be the response. Expected behavior A response with JSON data of tokens generated by the backend Screenshots A screenshot of the error in vscode thunder client. Django Version: 4.0.1 drf-social-oauth2: 1.2.1 Google Auth system: New Google Identity Services Additional context I used to work with the Old gapi.$Auth system. The issue appears to be coming from ConvertTokenView class in site-packages/drf_social_oauth2.py. When a user registers for the first time, these are the … -
Django Rest Framework Choices Field Serializer -- I'd like to get second element in a tuple
This is a model class BookModel(models.Model): """The model to represent books.""" class BookRating(models.IntegerChoices): AWFUL = 0, 'Awful' BAD = 1, 'Bad' NORMAL = 2, 'Normal' GOOD = 3, 'Good' GREAT = 4, 'Great' AWSOME = 5, 'Awesome' rating = models.PositiveSmallIntegerField(choices=BookRating.choices, null=True, blank=True) And this is a serializer Class BookSerializer(serializers.ModelSerializer): rating = serializers.ChoiceField(choices=BookModel.BookRating.choices, source='rating') class Meta: model = BookModel fields = '__all__' How do I serialize it properly in my case? I saw the answer here were we somone used a tuple of tuples and it worked with the logic I have, but idk how to do it when I use another class's choices for creating choices (sorry for tautology) -
Django Token Authentication doesn't work when I access to server via domain name
I have a Django application with token authentication and I serve it via Apache2. When I do my auth required requests to the server with the domain name it returns with 401 Unauthorized HTTP error. When I do it with ip:port, it returns success. Same token is sent to the server. What might cause that? May apache server be related to this? -
Django/Apache2 ALLOWED_HOSTS settings doesn't work
I have my ALLOWED_HOSTS configured as below in my settings.py file: ALLOWED_HOSTS = [ 'localhost', 'semanticspace.io', 'www.semanticspace.io' ] I also configured apache2 ServerName as below: ... ServerName semanticspace.io ServerAlias www.semanticspace.io ... Despite these, when I try to access my web page it gives this error: Invalid HTTP_HOST header: 'www.semanticspace.io'. You may need to add 'www.semanticspace.io' to ALLOWED_HOSTS. What might be the cause of that? -
Why am i having AttributeError: 'QuerySet' object has no attribute 'answer' on django serializer "PUT" method
I am trying to update the nested serializer in it but, it saying queryset has no attribute, this is the code below , please help out. Views.py class QuizQuestionDetail(APIView): def get(self, request, format=None, **kwargs): quizz = Question.objects.filter(id=kwargs['pk']) serializer = QuestionSerializer(quizz, many=True) return Response(serializer.data) def put(self, request, format=None, **kwargs): quizz = Question.objects.filter(id=kwargs['pk']) serializer = QuestionSerializer(quizz, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer.py class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = [ 'id', 'answer_text', 'is_right', ] class QuestionSerializer(serializers.ModelSerializer): answer = AnswerSerializer(many=True) class Meta: model = Question fields = ['id','quiz', 'title','answer', ] def create(self, validated_data): answers_data = validated_data.pop('answer') question = Question.objects.create(**validated_data) for answer_data in answers_data: Answer.objects.create(question=question, **answer_data) return question def update(self, instance, validated_data): answers_data = validated_data.pop('answer') answer = instance.answer.all() answers = list(answer) instance.quiz = validated_data.get('quiz', instance.quiz) instance.title = validated_data.get('title', instance.title) instance.save() for answer_data in answers_data: answer = answers.objects.get(pk=answer_data['id']) answer.answer_text = answer_data.get('answer_text', answer.answer_text) answer.is_right = answer_data.get('is_right', answer.is_right) answer.save() return instance -
List of forms in django
i'm trying to create a list of items that belong to a specific contract of a user in django. In this list, the user must be able to acces a form with all the items that belong to this specific contract, and edit their value. I've tried to use formsets, but the Items are not related to the contract, despite of a M2M field in the contract itself, so the error that i've been facing is: 'contract_generator.Item' has no ForeignKey to 'contract_generator.ClientContract'. The are the models that are in use: class ClientContract(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) original_contract = models.ForeignKey(Contract, on_delete=models.CASCADE, null=True, blank=True) contract_name = models.CharField(max_length=60) address = models.TextField(blank=True, null=True) # Value related information total_value = models.DecimalField(blank=True, null=True, max_digits=12, decimal_places=2) installments = models.IntegerField(null=True, blank=True) # Items and clausules of the contract items = models.ManyToManyField(Item, blank=True, null=True) clausules = models.ManyToManyField(Clausule, blank=True, null=True) def __str__(self): return self.contract_name class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item_name = models.CharField(max_length=90) item_type = models.CharField(max_length=90) item_value = models.FloatField(blank=True, null=True, max_length=12) item_qt = models.FloatField(blank=True, null=True, max_length=12) item_total = models.FloatField(blank=True, null=True, max_length=12) # Unity options METERS = 'MT' LITERS = 'LT' UNITY_CHOICES = [ (METERS, 'Meters'), (LITERS, 'Liters'), ] unity = models.CharField(choices=UNITY_CHOICES, default=METERS, max_length=20) def __str__(self): return self.item_name This is the … -
How can I quickly delete entries that should not exist in the database?
Imports entries from the old database. I download a specific object by name and these are objects taken from the old database. Now I check if such an object exists in the new database. There are, for example, 20 such old objects and 25 in the new base. How can I automatically remove these 5 objects from the new database? I tried something by using for e.g. obj = Model.objects.all() kr = Model.objects.filter(name=name).first() obj_list = [] for op in obj: if op in obj_list: continue else: obj_list.append(op) spec_list = [] for item in obj_list: if kr == item: continue else: spec_list.append(item) -
How can I get all Django groups and optionally get associated user record?
This should be pretty simple since it's very simple with pure SQL. I have the following query which gets exactly what I want in Django: SELECT auth_group.id, auth_group.name, auth_user.username FROM auth_group LEFT JOIN auth_user_groups ON auth_group.id = auth_user_groups.group_id LEFT JOIN auth_user ON auth_user_groups.user_id = auth_user.id WHERE auth_user.id = 3 OR auth_user.id IS NULL; How can I get this result using the ORM properly?