Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add comments without authentification required
i just done comments on my website,and i want to do non-authorized comments,and dont know how to.My models looks like this class Comment(models.Model): article = models.ForeignKey(Product, on_delete = models.CASCADE, verbose_name='Page', blank = True, null = True,related_name='comments' ) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, verbose_name='Comment author', blank = True, null = True ) create_date = models.DateTimeField(auto_now=True) text = models.TextField(verbose_name='Comment text', max_length=500) status = models.BooleanField(verbose_name='Visible', default=False) and views.py like this def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): self.object = form.save(commit=False) self.object.article = self.get_object() self.object.author = self.request.user self.object.save() return super().form_valid(form) -
Django ORM: How to GROUP BY a field that "lives" in the bottom of a recursive model?
Let's say I have the following models: class Unit(models.Model): name = models.CharField(...) class PackageDescription(models.Model): lower_level = models.ForeignKey("self", null=True, ...) unit = models.OneToOneField(Unit, null=True, ...) class StockItem(models.Model): package_description = models.OneToOneField(PackageDescription, ...) I want to know the amount of unit names in a given StockItem queryset (qs). If we don't had this recursive nature, we could simply do something like: qs.values("package_description__unit__name").annotate(count=Count("package_description__unit__name")) However, a PackageDescription can have several levels, and the Unit "lives" in the bottom of the structure. How would I know, within DB level, the lowest level? And more than that: how can I GROUP BY such field? NOTE: I'm using PostgreSQL. -
django createView return UNIQUE constraint failed: answer_profile.user_id when i submited the form
I'm trying to add User profile for user's in my website when they finished creating a user registration form it will redirected the user to the Profile model where they will create a Profile for their account. I successfully created a user registration form and it works fine but when the form is submitted and redirected a new user to the Profile model where i use CreateView the form throws an error when i submitted the form. the error: IntegrityError at /CreateProfile/ UNIQUE constraint failed: answer_profile.user_id Or is there anyway i can create a custom User profile for all new user when they create an account in my app. Like Stack Overflow. When a user created an account using Github, Facebook or Gmail the Stack Overflow will create a custom User profile where you can edit it. I have successfully created an edit profile. my views: class CreateProfile(CreateView): model = Profile fields = ['profile_image', 'stories', 'website', 'twitter', 'location'] template_name = 'create.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (CreateProfile, self).form_valid(form) def register(request): if request.method == 'POST': username = request.POST['username'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password … -
How to create absolute url inside serializer
Freshly created image field has only relative url - ImageFieldFile My serializer image field - ImageField How can I get the full url to this file? Should i just iterate over serializer data and append my domain before path? - example -
Is s3direct still supported?
I am using Django on heroku. I use Amazon s3 for my file storage. I am trying to use https://github.com/bradleyg/django-s3direct solution for large file uploads. I did everything I the tutorial but the file widget doesn’t appear in my admin. Is this solution still supported? -
Why django create empty field?
Hello I have simple model: class Company(models.Model): name = models.CharField(max_length=150, unique=True, blank=False) fullname = models.CharField(max_length=250, blank=True, null=True) description = models.TextField(blank=True, null=False) ... And I created simple test: ... def test_create_company_fail_name(self): """ Why create empty name Models!""" payload = { 'fullname': 'Test2Django', 'description': 'Simple test', 'country': 'Poland', 'city': 'Gdynia' } company = Company.objects.create(**payload) self.assertEqual(Company.objects.count(), 1) Why django create model if it didn't get field 'name'? But when I create model in admin section then I get error 'Field is require'. -
How to assign ForeignKey MySQL item in views.py?
When I save my NoteForm, I want to save my form and the "note" field, then I want to create a "tag" for the Note in the NoteTagModel. At the moment, I create a new tag but it is not assigned to the note. I know that the following code must be wrong: notetag.id = new_note_parse.id If I change to: notetag.note = new_note_parse.id I receive the following error: "NoteTagModel.note" must be a "NoteModel" instance. The below is my views.py: def notes(request): note_form = NoteForm notetag = NoteTagModel() note_form=NoteForm(request.POST) if note_form.is_valid(): new_note = note_form.save(commit=False) new_note_parse = new_note new_note.save() notetag.id = new_note_parse.id notetag.tag = "Test" notetag.save() return HttpResponseRedirect(reverse('notes:notes')) context = { 'note_form' : note_form, 'notes' : NoteModel.objects.all(), 'notes_tag' : NoteTagModel.objects.all(), } return render(request, "notes/notes.html", context) My models.py is: class NoteModel(models.Model): note = models.CharField( max_length = 5000 ) def __str__(self): return f"{self.note}" class NoteTagModel(models.Model): note = models.ForeignKey( NoteModel, on_delete=models.CASCADE, related_name="notes", blank= False, null = True, ) tag = models.CharField( max_length = 5000 ) def __str__(self): return f"Note: {self.note} | Tag: {self.tag}" I have the following as my forms.py: class NoteForm(ModelForm): class Meta: model = NoteModel fields = [ 'note', ] Any help would be greatly appreciated -
Django | Get count of articles per month
I got two models Article and Author implemented like this: class Author(models.Model): name = models.CharField(max_length=50) class Article(models.Model): name = models.CharField(max_length=50) author = models.ForeignKey(Author, on_delete=models.CASCADE) pub_date = models.DateField() On my template I want to plot a graph (using chart.js on the frontend side) showing the authors publications per month, for the last 12 months. For that I need the count of articles published each month. This is the query to get the authors articles: articles = Article.objects.filter(author=author) What would be best practice to get the count per month? I've thought about annotating each of the twelve month separately to the QuerySet, but haven't found a way that works for me. Alternatively, I thought about dealing with this on the JS site in the users browser. Any suggestions/recommendations? -
How to Replace All __prefix__ Placeholder Strings within Django Formsets empty_form Elements Using Only Javascript?
Django formsets have an empty_form attribute. empty_form BaseFormSet provides an additional attribute empty_form which returns a form instance with a prefix of __prefix__ for easier use in dynamic forms with JavaScript. The Django documentation doesn't actually say how to replace the __prefix__ with Javascript. Several online examples show how to do it with jQuery, but I specifically want to do it with Javascript - no jQuery. Here is the resulting HTML from my {{ formset.empty_form }}: <div id="prerequisiteEmptyForm"> <input type="text" name="prerequisites-__prefix__-text" maxlength="100" id="id-prerequisites-__prefix__-text"> <label for="id-prerequisites-__prefix__-DELETE">Delete:</label> <input type="checkbox" name="prerequisites-__prefix__-DELETE" id="id-prerequisites-__prefix__-DELETE"> <input type="hidden" name="prerequisites-__prefix__-id" id="id-prerequisites-__prefix__-id"> <input type="hidden" name="prerequisites-__prefix__-content" value="21" id="id-prerequisites-__prefix__-content"> </div> Everywhere it shows __prefix__, I want to replace it with a number... let's say 321. Correct solution: <div id="prerequisiteEmptyForm"> <input type="text" name="prerequisites-321-text" maxlength="100" id="id-prerequisites-321-text"> <label for="id-prerequisites-321-DELETE">Delete:</label> <input type="checkbox" name="prerequisites-321-DELETE" id="id-prerequisites-321-DELETE"> <input type="hidden" name="prerequisites-321-id" id="id-prerequisites-321-id"> <input type="hidden" name="prerequisites-321-content" value="21" id="id-prerequisites-321-content"> </div> So my question becomes Using Javascript only, how do I replace a constant value ("__prefix__") with something else ("321") across several elements (inputs and labels) within multiple attributes (name, id)? Specifically, I want to do it cleanly for repeatability. I don't want a highly custom solution to this specific problem. It needs to be a general approach... since this is replacing … -
How can i add a footer at the end of the website which is contains for loop in html?
I used : .footer{ position: relative; height: 130px; clear: both; background-color: red; to set a footer at the end of the website but now the footer is not at the end of the all products: html: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'main.css' %}"> </head> <body style="background-color: #36454F;"> {% for i in p%} <div class='card'> <div class="number">{{i.Number}}</div> <img src="{{i.image}}"></img> <p id="id">{{i.description}}</p> <a href="{{i.buy}}" target='_blank' rel='noopener noreferrer'> <button><span class="price"> ${{i.price}}</span> buy</button> </a> </div> {%endfor%} <div class="footer"> <h3>hello</h3> </div> </body> </html> css: .card { max-width: 400px; margin: 0auto; text-align: center; font-family: arial; border-style: solid; border-width: 6px; position: relative; top: 611px; margin-bottom: 33px; margin-right: 33px; justify-content: center; float: left; } .footer{ position: relative; height: 130px; clear: both; background-color: red; } .card img{ height: 400px; width: 400px; vertical-align: middle; } .price {background-color: #f44336; font-size:22px; border-radius: 3px; position: absolute; bottom: 0px; right: 0px; padding: 3px; } .card button { border: none; color: white; background-color: #000; position: relative ; cursor: pointer; width: 100%; height: 100px; font-size: 44px; align-items: center; } .card button:hover { opacity: .5; background-color: #330; } #id{ background-color: palevioletred; color: white; margin: 0; font-size: 17px; } .number{ width: 50px; height: 50px; background-color: #330; color: yellow; border-radius: 50%; position: … -
how to override django/wagtail url path in nginx?
I want to run several wagtail blogs on my server. The code i have is based on a couple of containers for each blog : one nginx container for the frontend and one container for the backend. I would like to serve both containers on one port with the nginx frontend served on / and the backend accessible on /wagtail so i could access to the admin at /wagtail/cms-admin. However when i use this config file for my nginx: server { listen 80; server_name localhost; location / { root /usr/share/nginx/html/storybook-static; index index.html index.htm; try_files $uri $uri/ /index.html; } location /wagtail { proxy_pass http://172.20.128.2:8000;#wagtail server running there proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 20M; } location /static/ { alias /app/static/; } location /media/ { alias /app/media/; } } the wagtail throws me a msg error "not found". I'm wondering if i dont need to configure something in my wagtail/django files so it recognizes it is served at /wagtail? Any hint on what i'm missing in the configuration? -
TypeError: byte indices must be integers or slices, not str & status code 500
I'm building an e-commerce site using ReactJS and Django (using redux) I'm trying to send a post request to my DB but I'm getting the following error: firstName = data['firstName'], TypeError: byte indices must be integers or slices, not str [31/May/2022 16:56:55] "POST /api/create/ HTTP/1.1" 500 63122 Here is my code: View.js api_view(['POST']) @csrf_exempt def createCitizen(request): data = request.body citizens = Citizen.objects.create ( firstName = data['firstName'], lastName = data['lastName'], dateOfBirth = data['dateOfBirth'], address = data['address'], City = data['City'], zipCode = data['zipCode'], cellular = data['cellular'], landLine = data['landLine'], hadCovid = data['hadCovid'], previousConditions = data['previousConditions'] ) serializer = CitizensSerializer(citizens, many=True) serializer.save() return JsonResponse(serializer.data, safe=False) The relevant part in RegisterPage.js const submitHandler = (e) => { e.preventDefault(); dispatch(createCitizens({ firstName, lastName, dateOfBirth, address, City, zipCode, cellular, landLine, hadCovid, previousConditions })) } return ( <Form onSubmit={submitHandler}> <Row> <h4>Please enter your information:</h4> </Row><br></br><Row className="mb-3"> <Form.Group as={Col} controlId="firstName"> <Form.Label>First Name</Form.Label> <Form.Control placeholder="Enter first name" required value={firstName} onChange={(e) => setFirstName(e.target.value)} /> </Form.Group> ... citizenAction.js export const createCitizens = (citizens) => async (dispatch) => { try { dispatch({type: 'CITIZEN_CREATE_REQUEST'}) const {data} = await axios.post('/api/create/', citizens) dispatch({ type: 'CITIZEN_CREATE_SUCCESS', payload: data }) } catch (error) { dispatch({ type: 'CITIZEN_CREATE_FAIL', payload: error.response && error.response.data.message ? error.response.data.message : error.message, }) } } … -
How to view the human readable Text in Enum Choices Django Models?
I have orders model init I have Status Enum Class I want to show the readable Text How ? models: from django.utils.translation import gettext_lazy as _ class Order(models.Model): class OrderStatus(models.TextChoices): Paid = "P", _("Paid") Shipping = "S", _("Shipping") Done = "D", _("Done") id = models.AutoField(primary_key=True) customer: User = models.ForeignKey(User, on_delete=models.CASCADE) product: Product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.PositiveIntegerField() status: OrderStatus = models.CharField( max_length=2, choices=OrderStatus.choices, default=OrderStatus.Paid ) created_time = models.DateTimeField(auto_now_add=True) last_updated_time = models.DateTimeField(auto_now=True) def __str__(self) -> str: status = Order.OrderStatus(self.status) return f"{self.customer.username}-{status.label}" @property def total_price(self) -> float: return self.amount * self.product.price def get_absolute_url(self) -> str: return reverse("get_order", kwargs={"pk": self.id}) is there something I need to write in my template to Get it or Where is the Problem ? template Code : <td>{{order.status}}</td> -
how to search foreign field in Django RestFramework Api?
I am trying to apply foreign field search function in django restFramework api. like shown in below class SearchborrowList(ListAPIView): queryset = borrow.objects.all() serializer_class = borrowserializer filter_backends = [SearchFilter] search_fields = ['student'] in this search fields = ['student'], student field is foreign field. When I search its show an error Related Field got invalid lookup: icontains how can I retrieve foreign field when search. -
Am trying to save user radio button input of an html form to my database
please am new to django, and am trying to save user radio button input of an html form to my database by category have created for different post using CBV, i really don't know how to go about please i need help , thanks in advance here is my models.py ' class Data(models.Model): 'name= models.CharField(max_length=50, default='') data=models.CharField(max_length=50 ,blank=True,null=True) `class Category(models.Model): name =models.CharField(max_length=200,default='') class CandidateForm(models.Model): image= models.ImageField(upload_to='images/', width_field=None,default=0) data=models.ForeignKey(Data,blank=True,null=True,on_delete=models.PROTECT) category=models.ForeignKey(Category,blank=True,null=True,on_delete=models.PROTECT) Nickname=models.CharField(max_length=100,default='') Name=models.CharField(max_length=100,) def __str__(self): return self.Nickname here is my views.py def vote_data(request): if request.method == 'POST': post=models.Data() post.data=models.Category.objects.filter(name='category') post.name=request.POST['candidate'] post.save() return redirect('Home') and lastly, the category.html page <form action="{%url 'data' %}" method="POST" name=""> {% csrf_token %} {% for candidate in Post.candidate %} <div class=".col-md-4-flex" data-aos="zoom-out"> <div class="position-relative"> <img src="{{candidate.image.url}}"> <p>{{candidate.Name}}</p> <label for="candidates_{{candidate.Nickname}}" class="radio-inline"> <input type="radio" name="candidate" value="{{candidate.Nickname}}" id="candidates_{{candidate.Nickname}}">{{candidate.Nickname|upper}} </label> </div> {% endfor %} </div> <input type="submit" value="submit"> sorry for uneccessary information. -
Django MultiSelectField Selected Choice Yields "Not a Valid Choice" Error
I am new to Django and have a MultiSelectField in my Meal Model. I am also utilizing a MultipleChoiceField with widget CheckBoxSelectMultiple in my Meal Form. When I select a checkbox in the Template and POST the form, I get an error which states, "[ValidationError(["Value ['CHICKEN CASSEROLE'] is not a valid choice."])]}). I am wondering what I am doing wrong here and need some assistance in figuring this out. Any help is appreciated. Below is my code for my Model and Form: class Meal(models.Model): day = models.CharField(max_length=255, blank=True) category = models.CharField(max_length=100, blank=True) meal_time = models.TimeField(null=True, blank=True, verbose_name='Meal Time') recipes = MultiSelectField(max_length=5000, choices=[], null=True) meal_id = models.IntegerField(null=True, blank=True) menu = models.ForeignKey(Menu, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return "%s %s %s %s" % ( self.day, self.category, self.meal_time, self.recipes) class Meta: app_label = "mealmenumaster" managed = True class MealForm(forms.ModelForm): day = DynamicChoiceField(choices=[], required=False) category = forms.ChoiceField(choices=(('', 'None'),) + CATEGORY, required=False) recipes = forms.MultipleChoiceField(label="Select Recipe(s)", widget=forms.CheckboxSelectMultiple(), required=False) meal_id = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: widgets = {'meal_time': TimeInput()} model = Meal fields = ['day', 'category', 'meal_time', 'recipes', 'meal_id'] app_label = "mealmenumaster" def __init__(self, *args, **kwargs): user_id = kwargs.pop('user_id', None) super(MealForm, self).__init__(*args, **kwargs) self.fields['recipes'].choices = [(x.name, x.name) for x in … -
How to get Checkbox Select Multiple for profile page
Beginner here in Django. Goal: I would like to get a multiple checkbox selection for favorite categories and save those in the database. Problem Right now I have a profile form and model, and the CheckboxSelectMultiple widget is not working like I want it to work. The categories are stored in another model which I reference in the user profile. # # # # user/forms/profile_form.py class ProfileForm(ModelForm): class Meta: model = Profile exclude = [ 'id', 'user'] widgets = { 'favourite_categories': widgets.CheckboxSelectMultiple(attrs={'class': 'form-control'}), 'profile_picture': widgets.TextInput(attrs={'class': 'form-control'}) } # # # # user/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) favorite_categories = models.ManyToManyField(Category, blank=True) profile_image = models.CharField(max_length=200, null=True, blank=True) # # # # user/views.py @ login_required def profile(request): user_profile = Profile.objects.filter(user=request.user).first() if request.method == 'POST': form = ProfileForm(instance=user_profile, data=request.POST) if form.is_valid(): user_profile = form.save(commit=False) user_profile.user = request.user user_profile.save() return redirect('profile') return render(request, 'user/profile.html', context={"form": ProfileForm(instance=user_profile)}) # # # # templates/user/profile.html <div class="shadow p-4 mb-5 mx-5 bg-body rounded"> <form class="form form-horizontal" method="post"> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn btn-primary" value="Update" /> </form> </div> The output of this can be seen in the picture. PS. I also don't know how to use ImageField … -
'django-admin help' Fatal error in launcher: Unable to create process
When I try to run "django-admin help" or any other django-admin command in the vscode terminal (within the virtualenv) it gives me the following error : Fatal error in launcher: Unable to create process using '"F:\DevOps\Django\btre_project\venv\Scripts\python.exe" "F:\Django\btre_project\venv\Scripts\django-admin.exe" help': The system cannot find the file specified. The whole Django project was located in F:\DevOps first but then I moved the Django folder outside the F:\DevOps so it's now at this location currently "F:\Django". Virtual environment can be activated and deactivated perfectly and also if I start the server with "python manage.py runserver" The server is up and running. But whenever I try to run the django command it gives me the above error. Also, in the virtual environment of project django is installed and I also tried reinstalling the django in the virtualenv with pip but nothing worked out and I get the same error. Any help would be appreciated, thanks. -
hi, I am using python3 for one of my project and I am getting msilib module error. I am using Mac. and when ever I start my server I am getting error
I am getting some module error while try to run the server for python develop on Django enter image description here -
React problems with updating state
I'm new to React and trying to build a twitter like app for this project https://cs50.harvard.edu/web/2020/projects/4/network/. This is my code: function App (){ const [state, setState] = React.useState({ view: Allpostsview, newpost: '' }); function Navitem(props){ return( <a class="nav-link" style={{cursor:'pointer'}} onClick={()=>loadNewpage(props)}>{props.content}</a> ) } if(document.querySelector("#newpost")){ ReactDOM.render(<Navitem content='New Post' view={Newpostview} />, document.querySelector("#newpost")); } if(document.querySelector("#allposts")){ ReactDOM.render(<Navitem content='All Post' view={Allpostsview}/>, document.querySelector("#allposts")); } if(document.querySelector("#user")){ ReactDOM.render(<Navitem content='Username' view={Userview}/>, document.querySelector("#user")); } if(document.querySelector("#following")){ ReactDOM.render(<Navitem content='Following' view={Followingview}/>, document.querySelector("#following")); } function loadNewpage(props){ setState({ ...state, view: props.view }); } function Allpostsview(){ return( <h1>All Posts</h1> ); } function Newpostview(){ return( <div className="formgroup functionDiv"> <h2>New Post</h2> <textarea className="form-control" rows="3" onChange={()=>handleText(event)}></textarea> <button className="btn btn-primary" onClick={()=>handelNewpost()}>Post</button> </div> ); } function handleText(event){ console.log(event.target.value) console.log(state) setState({ ...state, newpost: event.target.value }); } function handelNewpost(){ console.log('handleNewpost') } function Followingview(){ return( <h1>Following</h1> ); } function Userview(){ return( <h1>Username</h1> ); } return( <state.view /> ) } if(document.querySelector("#app")){ ReactDOM.render(<App />, document.querySelector("#app")); } I have two problems When I try to debug the code with the chrome extensions Components feature, my Navitems stop working I'm currently working on the new post feature. The function handleText shows me that my state is whatever view I was in before I clicked on new post. Therefore, when I try to enter text the view always changes. I'm … -
Django - How to save individual elements of a CharField when a form is submitted?
When I submit my form, I want the text submitted as "note" to be split up, say by paragraph, and also saved to the "tag" part of my model automatically. I have the following as my models.py class NoteModel(models.Model): note = models.CharField( max_length = 5000 ) def __str__(self): return f"{self.note}" class NoteTagModel(models.Model): note = models.ForeignKey( NoteModel, on_delete=models.CASCADE, related_name="notes", blank= False, null = True, ) tag = models.CharField( max_length = 5000 ) def __str__(self): return f"Note: {self.note} | Tag: {self.tag}" I have the following as my forms.py class NoteTagForm(ModelForm): class Meta: model = NoteTagModel fields = [ 'note', ] Is there a way of doing this with Signals? Or would using a hidden inline formset be the best way? Any other suggestions are greatly appreciated. I appreciate that JavaScript may be needed to separate out the text and declare as a variable to be saved as a form value. Many thanks -
djangorestframework-simplejwt with auth0 - settings issue?
environment: django (4.0.4) rest_framework (3.13.1) djangorestframework-simplejwt (5.2.0) What are the exact settings that should be used with simplejwt+auth0? I cannot find any example and unfortunately i've failed to figure it out by myself. I have tried the following: AUTH0_DOMAIN = 'dev-demo-xxxx.auth0.com' API_IDENTIFIER = 'xxxxx' PUBLIC_KEY = None JWT_ISSUER = None if AUTH0_DOMAIN: jsonurl = request.urlopen('https://' + AUTH0_DOMAIN + '/.well-known/jwks.json') jwks = json.loads(jsonurl.read().decode('utf-8')) cert = '-----BEGIN CERTIFICATE-----\n' + jwks['keys'][0]['x5c'][0] + '\n-----END CERTIFICATE-----' certificate = load_pem_x509_certificate(cert.encode('utf-8'), default_backend()) PUBLIC_KEY = certificate.public_key() JWT_ISSUER = 'https://' + AUTH0_DOMAIN + '/' SIMPLE_JWT = { 'ALGORITHM': 'RS256', 'AUDIENCE': 'https://issuer-domain', 'ISSUER': JWT_ISSUER, 'VERIFYING_KEY': PUBLIC_KEY } but tokens that are sent from client (retrieved successfully using auth0 javascript library) are not verified properly on the backend. (token has been successfully verified using jwt.io debugging tool) current error: code: "token_not_valid" detail: "Given token not valid for any token type" -
Selecting first item in a subquery of many to many relationship in django
Consider having a Book model with many Comments (from different Users) which may belong to many Categories. class Category(Model): title = CharField(max_length=200) class Book(Model): title = CharField(max_length=200) categories = ManyToManyField(Category) class User(Model): name = CharField(max_length=200) class Comment(Book): content = TextField() book = ForeignKey(Book, null=False, on_delete=CASCADE) user = ForeignKey(User, null=False, on_delete=CASCADE) I want to select comments for an specific Book, and for each Comment, annotate it with the number of comments that the writer of that Comment wrote for the first Category of that book. And I want to this in a single query. Something like this: def get_commnets(book): main_category = book.categories.first() n_same_comments_subquery = Subquery( Comments.objects .filter(user__id=OuterRef('user_id'), book__category__first=main_category) .annotate(count=Count('pk')) .values('count') )[:1] comments = ( book.comment_set .annotate(n_same_comments=n_same_comments_subquery) ) return comments The previous piece of code does not work, obviously. This is because there is not any lookup like first. I've tried many other solutions, but non of them worked. How can I achieve this goal? Thank you in advance. -
Django override __init__ form method using ModelForm
I have a foreign key (zone_set) as a choice field in a form. It should only display current project's zone_set . As you can see, It is not the case since it's displaying a zone_set: I belong to an other project, I should not be displayed here which does not belong to the current project. Any help please ! Here is my form but it doesn't work class ODMatrixForm(forms.ModelForm): class Meta: model = ODMatrix # fields = '__all__' exclude = ('size', 'locked',) def __init__(self, current_project=None, *args, **kwargs): super().__init__(*args, **kwargs) if current_project: queryset = ZoneSet.objects.filter(project=current_project) self.fields['zone_set'].queryset = queryset -
How to stop adding
How can I prevent adding an object if there is an exact same object in the cell room_bool == False in Django rest api models.py class Rooms(models.Model): objects = None room_num = models.IntegerField(verbose_name='Комната') room_bool = models.BooleanField(default=True, verbose_name='Релевантность') category = models.CharField(max_length=150, verbose_name='Категория') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Комнату' verbose_name_plural = 'Комнаты' class Registration(models.Model): objects = None rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE, verbose_name='Номер', help_text='Номер в который хотите заселить гостя!', ) first_name = models.CharField(max_length=150, verbose_name='Имя') last_name = models.CharField(max_length=150, verbose_name='Фамилия') admin = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Администратор',related_name='admins') pasport_serial_num = models.CharField(max_length=100, verbose_name='Серия паспорта', help_text='*AB-0123456') birth_date = models.DateField(verbose_name='Дата рождения') img = models.FileField(verbose_name='Фото документа', help_text='Загружайте файл в формате .pdf') visit_date = models.DateField( default=django.utils.timezone.localdate, verbose_name='Дата прибытия') leave_date = models.DateField(blank=True, null=True, verbose_name='Дата отбытия', default='После ухода!') guest_count = models.IntegerField(default=1, verbose_name='Кол-во людей') room_bool = models.BooleanField(default=False, verbose_name='Релевантность', help_text='При бронирование отключите галочку') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.rooms},{self.last_name},{self.first_name},{self.room_bool},{self.admin}' class Meta: verbose_name = 'Номер' verbose_name_plural = 'Регистрация' views.py class RegCreate(CreateAPIView): queryset = Registration.objects.all() serializer_class = RegSerializer serializers.py class RegSerializer(serializers.ModelSerializer): admin = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Registration exclude = ['price', 'visit_date']