Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix Cannot assign "": "" must be a "" instance? when it is created in view?
I want to create model with view when the user is created, but I got and error: Cannot assign "<User:test1234": "Customer_info.customer" must be a "Customer" instance. Here are the models that I have and which I want to be created automatically when user is registered. class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) points = models.FloatField(default = 0.0) ... class Customer_info(models.Model): customer = models.OneToOneField(Customer, on_delete=models.CASCADE) deposit = models.FloatField(default = 0.0) And in views.py after registering those models are creating def reg(request): form = CreateUserForm() if "register-btn" in request.POST: form = CreateUserForm(request.POST) if form.is_valid(): new_user = form.save() login(request, new_user) Customer.objects.create( user=new_user, points=0.0 ) Customer_info.objects.create( customer = new_user, deposit = 0.0 ) response = redirect('profile') return response return render(request, 'main.html') -
Making website responsive to devices other than desktop pc
I've been tasked to try and make my friend a portfolio website(my real first project). I think I've made a mistake of only focusing on designing for desktop and forgetting about other devices. Here's a link to the site so you can see how it is responding; https://vsworldtest.herokuapp.com/ As you can see its not responding as I would like it when loading on a mobile phone. Still some tweaks needed and some cleaning of the css for desktop but it is more than viable for testing at the moment. If you have any idea of what I could do to make this responsive for mobile devices and tablets please share with me. Code to follow: CSS <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, user-scalable=0"> <title>vstheWorld</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"/> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"> </script> <style> @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap'); * { box-sizing: border-box; } .container-top { margin: 500px; } hr { color: white; margin-bottom: 20px; } .banner-image { text-align: center; } body { {% load static %} background-image: url("{% static 'images/purple.jpg' %}"); padding: 15px; font-family: 'Roboto', sans-serif; font-weight: bold; background-repeat: no-repeat; background-size: 100% 200%; position: relative; } /* Center website */ main { max-width: 100%%; … -
How do you create a function to check the attribute of another field in a separate model?
class Trait(models.Model): name = models.CharField(max_length=20) animal_types = models.ManyToManyField(AnimalType) # slots = models.CharField(default=None, null=True, max_length=4) #slots is meant to hold a value that determines where it can be placed in animal model #i.e. null means anywhere, "2" means only trait 2 #def TraitPlace(self): def __str__(self): return self.name #need to add animal details like age and gender to a separate model or integrate/hardcode into animal model as they're only 7 options class ANIMAL(models.Model): animal_type = models.ForeignKey(AnimalType, on_delete = models.CASCADE) first_trait = models.ForeignKey(Trait, on_delete = models.CASCADE) #first trait and animal required as animals always exist and have at least one trait # second_trait= models.ForeignKey(Trait, on_delete = models.CASCADE) # third_trait= models.ForeignKey(Trait, on_delete=models.CASCADE) I've got an animal model which is used to create an animal with up to 3 traits, the problem is that some traits have specific placement restrictions, i.e. "lithe" can only be in position 3, and glistening can only be in positions 2 and 3. It was suggested to add an additional "slots" field under the trait model. I understand logically how it's supposed to work out, but am struggling with implementation. I tried to look up documentation and use hasattr under my first_trait but that didn't work or I just didn't … -
How can I show payment update for a specific appointment?
So I'm trying to make a section under each appointment details that shows their payment transactions of the appointment specifically. all my tries so far didn't work, i can only show all payment updates which is not the wanted result obviously. this is the code: views.py def appointment_details(request, id): search_patient_form = SearchPatient() current_user_phone = request.session.get('user') current_user = get_object_or_404(Doctor, phone = current_user_phone) if current_user: if request.method == 'POST': searchPatient = SearchPatient(request.POST) if searchPatient.is_valid(): patient_id_phone = searchPatient.cleaned_data['patient_id_phone'] return redirect('search_patient', id_phone=patient_id_phone) else: appointment = get_object_or_404(Appointment, id = id) updates = PaymentUpDate.objects.all() return render(request, 'about-appointment.html', { 'current_user': current_user, 'sayfa': 'appointments', 'appointment': appointment, 'updates': updates, 'search_patient_form': search_patient_form }) else: return redirect('login') models.py This is the class the makes the updates class PaymentUpDate(models.Model): payment_date = models.DateTimeField(auto_now_add=True) payment_amount = models.CharField(max_length=550) I've tried doing the same approach as I did to show a specific appointment, which is: appointment = get_object_or_404(Appointment, id = id) to the updates, which looked something like : updates = get_object_or_404(PaymentUpDate, id = id) which resulted in the following error : TypeError at /appointment-details/3 'PaymentUpDate' object is not iterable and i also tried this guide: How to show every user specific payment for them in django?, which made my code look like this: class PaymentUpDate(models.Model): … -
How can I solve this indentation problem in my Django project
I'm a beginner in Django. I was trying to add a method inside the OrderItem class. But the visual studio code is showing an indentation error. I'm not sure what is wrong here. Anyone can help me, please? The indentation error is showing on the @property and get_total() ` class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total ` Pelase see the attached screenshot. -
How to filter exported data by a value on database using django export import
I want to export a student data from my database and filter it by roles column. Views.py def export_siswa(request): user = userResource() dataset = user.export() response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=Data_Siswa.xls' return response resource.py class userResource(resources.ModelResource): username = Field(attribute='username', column_name='Username') namadepan = Field(attribute='namadepan', column_name='Nama depan') namabelakang = Field(attribute='namabelakang',column_name='Nama belakang') email = Field(attribute='email',column_name='Email') jeniskelamin = Field(attribute='jeniskelamin',column_name='Jenis kelamin') tanggallahir = Field(attribute='tanggallahir',column_name='Tanggal lahir') agama = Field(attribute='agama',column_name='Agama') alamat = Field(attribute='alamat',column_name='Alamat') telepon = Field(attribute='telepon',column_name='Telepon') class Meta: model = modelUser fields = ['username','namadepan','namabelakang','email','jeniskelamin','tanggallahir','agama','alamat','telepon','role'] export_order = ['username','namadepan','namabelakang','email','jeniskelamin','tanggallahir','agama','alamat','telepon','role'] That is my code for the views and resource.py .. but they show all of the data .. i want the exported data is a student with "student" roles -
Django forms template dropdown with unique identifier for each iteration of a forloop
I am trying to generate a unique ID for each iteration of a for loop item. The item generated is a drop down menu and the number of times it s generated will depend on the number of incidents that are active. The the problem I am having is that the ID of the dropdown is the same for each dropdown menu. In this case id="id_status" when viewed via the browser page source Is there a way to generate for example id="id_status_1" for the first dropdown, then id="id_status_2" for the second one and so on? I tried to implement something with forloop.counter and also javascript's setAttribute("id", "uniqueIdentifier"), but have been racking my brain for hours now without success models.py from django.db import models ... ... class IncidentStatus(models.Model): status = models.CharField(max_length=128) def __str__(self): return self.status forms.py: from .models import IncidentStatus ... ... class IncidentStatusAssigneeForm(ModelForm): status = forms.ModelChoiceField(queryset=IncidentStatus.objects.all().order_by('status'), empty_label='Select a Status', label='') class Meta: model = IncidentStatus fields = ('status',) views.py: from .models import IncidentStatus from .forms import IncidentStatusAssigneeForm ... ... def set_status(req): all_statuses_a = IncidentStatusAssigneeForm() all_incidents = Incident.objects.all ... ... context = {'all_statuses_a': all_statuses_a, 'all_incidents': all_incidents, ....} return render(req, 'incident_main/assignee.html', context) template.html: {% for incident in all_incidents %} {{ all_statuses_a }} … -
Make an appointnment between a period of given time
I have a model Schedule, where doctor can set time of work. All appointments are gonna be for 30 min. What should I do? class Schedule(models.Model): doctor = models.OneToOneField('DoctorProfile', on_delete=models.CASCADE) WEEKDAYS = ( ('Mn', 'Понедельник'), ('Tue', 'Вторник'), ('W', 'Среда'), ('Th', 'Четверг'), ('Fr', 'Пятница'), ('St', 'Суббота'), ('Sn', 'Воскресенье'), ) weekday = MultiSelectField(max_length=5, choices=WEEKDAYS) start_time = models.TimeField() end_time = models.TimeField() -
VSCode Django HTML, JS, CSS guide for proper autocomplete and linting
I need some help here, hopefully in the proper place for this. Googled my eyes out in the last few weeks but havent come across a proper solution to configure VSCode properly. There is tons of talented coders out the who make awesome extensions, but its getting overwhelming and confusing sometimes. Im learning Python and Django, unable to have proper Linting and autocorrect to work with Django HTML. Found many bits of pieces on one or other part configurations but looking for something complete. Bootstrap, CSS, Javascript autocomplete not working when document type set to Django HTML or Django template tags not working when set to HTML. What is the best configuration for Python, Javascript, CSS, Django HTML ? I like to auto suggest of Bootstrap classes, JavaScript snippets and CSS properties but they dont work when Django HTML selected, the opposite when doc type set to HTML. Loosing my mind over this and probably need to delete all VSCode config or even the whole app and start it fresh but looking for a proper guide/tutorial to follow first.... -
Attach, display and submit forms to each product id displayed within a for loop (Django)
I am looking to integrate a form to each product, included within a loop. Each form is independent for the others: if one form is submitted, the others wont need to be. Currently the form is not validating. I think it's because I haven't managed to attach the form to the specific product id and I am not sure how to do that. When applying a form to a specific Id on a single page, I would simply proceed with def function(request, product_id). This is not an option here, as I am displaying several products on the same page. models.py class ReviewRating(models.Model): user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE, related_name="usercomments") product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) review =models.TextField(max_length=250, blank=True) rating =models.IntegerField(choices=RATING, default=0) forms.py class ReviewForm(forms.ModelForm): venue = forms.ModelChoiceField(queryset = Venue.objects.all(),required=False) class Meta: model = ReviewRating fields = ['review', 'rating','venue'] widgets = { 'venue': forms.TextInput(attrs={'class':'form-select', 'placeholder':'Enter name'}), } views.py def show_event(request, event_id): submitted = False form = '' form = 'ReviewForm' if request.method =="POST": form = ReviewForm(request.POST) if form .is_valid(): data = form .save(commit=False) data.product_id = product_id #<-- How do I define product_id? data.user_id = request.user.id data.save() else : print(form .errors) else: form = ReviewForm() event = Event.objects.get(pk=event_id) categories = Product.objects.filter(event=event_id) menu = event.product.filter(event=event_id) return render(request, 'main/show_event.html',{'event':event, 'categories':categories,'menu':menu,'form':form,'submitted':submitted}) … -
How can I download an audio mp3 file and save it?
My View: class UserSearchView(APIView): def get(self, request, link): url = config('BASE_URL') querystring = {"track_url": f'{link}'} headers = { "X-RapidAPI-Key": config('API_KEY'), "X-RapidAPI-Host": config('API_HOST') } response = requests.request("GET", url, headers=headers, params=querystring) data = response.json() return JsonResponse(data) My response : { "url": "https://result.s3.amazonaws.com/2022-11-13/61566981.mp3" } Not sure how to proceed here, can anyone help ?---------------------- -
Deploy django as a api url using nginx and gunicorn
I am using Django with Gunicorn and Nginx. I have a domain and i want Django to point to domain/api. I am able to point the Django to domain/api but Django complains that /api path is not found. Ideally i don't want to create /api url in django. i want domain/api to point to django home page. Below is the current nginx configuration. server { location /api { try_files $uri @proxy_api; } location /admin{ try_files $uri @proxy_api; } location @proxy_api { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_set_header X-Url-Scheme $scheme; } -
How to deploy Django App on Ubuntu using Apache2 and mod-wsgi-pytho3
I am trying to deploy my Django App on AWS by following this article Link of the article. I have done almost same but getting this error [Sun Nov 13 16:02:45.432532 2022] [wsgi:error] [pid 116628:tid 140699140834880] [remote 171.78.234.250:51518] ModuleNotFoundError: No module named 'bitssatoshiproject> here is my http conf file- ` <VirtualHost *:80> ServerAdmin ubuntu@172-31-11-19 ServerName 172-31-11-19 ServerAlias 172-31-11-19.com ErrorLog /home/ubuntu/site/logs/error.log CustomLog /home/ubuntu/site/logs/access.log combine <Directory /home/ubuntu/BitsSatoshi/bitssatoshiproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess bits python-home=/home/ubuntu/bitsvenv python-path=/home/ubuntu/BitsSatoshi/ WSGIProcessGroup bits WSGIScriptAlias / /home/ubuntu/BitsSatoshi/bitssatoshiproject/wsgi.py </VirtualHost> ` Please help me out guy, I am trying since so many days. I tried every guide on google but no success and don't even know I am wrong. But one thing is for sure that the wsgi is not getting my virtual environment python. -
Unable to upload images as Django admin
This is the models.py code to define the field type and to accept the input of type image car_photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d') car_photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) defined the below code in settings.py file MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' the below line is added in the urls.py file + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) but when I run the program and click on upload image for car_photo_1 the upload option is greyed out so I'm unable to save the input. Can someone assist on how to proceed here? -
Referral code and notification showing in user dashboard
I am new to python and Django. I have a Django website built where users can register/login and then have an account balance and account invested. Now I want to add a referral link to it where after the user registers it will give the user a link to send to another to register with and after registration, a notification will be shown in the user account showing all the people the user referred using his referral link. My code here https://github.com/onuonu1/magna -
Update model instance foreign key field upon creation of an instance of another model
I have two models, Profile, and BusinessProfile. One Business Profile can be accessed by multiple users (via profiles model which is linked to user model). I am trying to build so that the logged in user can create a business profile, which I have done. However, I am having trouble working out how to update the "Business" ForeignKey field within the Profile model, with the BusinessProfile id field as the value, upon creation of the BusinessProfile model instance by that user. Does anyone know how I can do this? My models.py are as follows: class BusinessProfile(models.Model): business_name = models.CharField(verbose_name='Business Name', max_length=255) business_description = models.TextField(verbose_name='Business Description', max_length=500) business_contact_number = models.CharField(verbose_name='Business Contact Number', max_length=32) business_email = models.EmailField(verbose_name='Business Email') address = AddressField(verbose_name='Business Address') creation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.business_name) class Profile(models.Model): MALE = 'M' FEMALE = 'F' OTHER = 'O' UNSPECIFIED = "U" GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other'), (UNSPECIFIED, 'Prefer not to say'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(verbose_name='Mobile Phone Number', max_length=20) bio = models.TextField(verbose_name='Bio', max_length=500, blank=True, null=True) date_of_birth = models.DateField(verbose_name='Date of Birth', blank=True, null=True) first_name = models.CharField(verbose_name='First Name', max_length=255, blank=True, null=True) surname = models.CharField(verbose_name='Surname', max_length=255, blank=True, null=True) gender = models.CharField(verbose_name='Gender', max_length=255, choices=GENDER_CHOICES, blank=True, null=True) emergency_contact_name … -
Can someone Explain what kind of table is this?
The Model and Table in my shell (https://i.stack.imgur.com/5Hagn.jpg)](https://i.stack.imgur.com/5Hagn.jpg) This is my django Model which i am going to update the admin credentials for a project i am working on it but i am facing this kind of Model (table) in sqlite3 and I don’t know what is it and how can i select the admin from this customerUser Table on shell to update it. -
Implementing django-recaptcha in Django project with a custom user and django-allauth
I need help implementing django-recapcha in a Django project that has a custom user and also has django-allauth. When I first set up this project I set up a custom user, as it is the recommendation from the official Django site.(https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project). After that I implemented django-allauth for authentication. Now I want to implement django-recapctha and I haven't found the right way to do it. I don't know how I should configure the forms.py file, because I don't understand well what is happening with this combination of custom user and django-allauth. Which is the form I should edit to configure django-recapcha and from which app? When I configured the custom user I did it as follows: I created an app called accounts. I created accounts/models.py with the following code: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): profile_pic = models.ImageField(default='default.jpg', upload_to='profile_pics') I created accounts/forms.py with the following code: from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ( 'email', 'username', ) class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields = ( 'email', 'username', ) Then I added the following to settings.py: AUTH_USER_MODEL = 'accounts.CustomUser' The django-recaptcha instructions indicate that I … -
unable to understand how the group name is defined based on the chat room name while making a chat application using channels
self.room_group_name = "chat_%s" % self.room_name This is the line of code that defines the room group name from the room_name in the official tutorial on the channels website. (https://channels.readthedocs.io/en/stable/tutorial/part_2.html) I am unable to understand what "chat_%s" % self.room_name" means. Would appreciate any explanation of what this bit of code exactly does. -
Nextcloud and Django (static) website aside behind nginx-proxy issue
First of all, i'm a beginner in networking and with web services in general. Context : i've a domain name : mydomain.com and a VPS server (with Ubuntu) with a fixed IPV4 adress : MYIPADRESS. In my VPS provider control panel , i've binded mydomain.com to MYVPSIPADRESS with an entry A. Only one domain is binded to MYIPADRESS. Objective : I want to host two webservices on my VPS : a nextcloud instance and my blog that is a Django static website, all set up with HTTPS. I want that my nextcloud instance points to cloud.mydomain.com and my blog Django instance to blog.mydomain.com. To do so, i'm using docker. Basically, i'm using the nginx-proxy server + its letsencrypt companion. Once done, i run my docker container for my django blog with env variables according to nginx-proxy documentation and put my blog container in the same network as nginx-proxy and its letsencrypt companion networks. At each time, without detaching my images , logs do not show me any warnings/"exited with 1"/red-written rows stuffs whether with blog container or nginx-proxy/letsencrypt companion container. I did not try to put my nextcloud instance so far since just my blog container setup does not work. … -
two upload file next to each other with texarea with bootstrap
I hava a django application. And I have two file upload boxes. And two textarea's. So I have it like this: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <link rel="stylesheet" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container"> <div class="inline-div"> <form action="/controlepunt140" method="POST" type="file" class="form-control form-control-lg" enctype="multipart/form-data" > <!-- <input type="file" id="img" name="img" accept=".pdf, .xlsx"> --> {% csrf_token %} {{ form }} <input type="submit" type="file" value="Verstuur" accept="application/pdf" /> </form> <textarea class="inline-txtarea" name="" id="" cols="70" rows="10"> {{content_pdf}}</textarea > </div> <div class="inline-div"> <form action="/controlepunt140" method="POST" type="file" class="form-control form-control-lg" enctype="multipart/form-data" > <!-- <input type="file" id="img" name="img" accept=".pdf, .xlsx"> --> {% csrf_token %} {{ form }} <input class="form-control" type="submit" type="file" value="Verstuur" accept="application/pdf" /> </form> <textarea class="inline-txtarea" name="" id="" cols="70" rows="10"> {{content_pdf}}</textarea > </div> </div> </body> </html> {% endblock content %} and css: .inline-div { display: inline-block; } .inline-txtarea { resize: none; border: 2px solid orange; height: 125px; } And in the fiddle looks like this: https://jsfiddle.net/SavantKing/nvuy92z5/ But in fiddle there is a button verstuur. So that is correct. But in the application the button … -
get error when want POST something to api{detail: "CSRF Failed: CSRF token missing."}
when i want to POST some thing to API , i get this error : CSRF TOKEN , but i don't have CSRF Token in django , i want POST without CSRF token i can POST with Postman but when i want post it by js , i get error that i said in first how can i do? let edit_data = { user_id: "1", company: "rahaaaa", description: "12343234234", first_name: "324234234234312sd", id_number: "122222", last_name: "32423dqwe32", } let c = JSON.stringify(edit_data) console.log(c); fetch("http://127.0.0.1:8000/api/postCustomer/", { headers: { "Content-Type": "application/json", }, method: "POST", body:c, }) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.log(err)); when i want to POST some thing to API , i get this error : CSRF TOKEN , but i don't have CSRF Token in django , i want POST without CSRF token how can i do? -
Django Rest Framework viewset mypy error: Missing positional argument
Here is a problem, when testing method from drf viewsets with @action() decorator, mypy gives error expecting additional argument (which is self param). Here it is: # views.py class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet): serializer_class = UserSerializer queryset = User.objects.all() lookup_field = "username" def get_queryset(self, *args, **kwargs): assert isinstance(self.request.user.id, int) return self.queryset.filter(id=self.request.user.id) @action(detail=False) def me(self, request: WSGIRequest): serializer = UserSerializer(request.user, context={"request": request}) return Response(status=status.HTTP_200_OK, data=serializer.data) # test_views.py def test_me(self, user: User, rf: RequestFactory): view = UserViewSet() request = Request(rf.get("/fake-url/")) request.user = user view.request = request response = view.me(request) # The problem is here assert response.data == { "username": user.username, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", } and the log is: drf_project\users\tests\test_drf_views.py:25: error: Missing positional argument "request" in call to "me" of "UserViewSet" drf_project\users\tests\test_drf_views.py:25: note: "__call__" is considered instance variable, to make it class variable use ClassVar[...] drf_project\users\tests\test_drf_views.py:25: error: Argument 1 to "me" of "UserViewSet" has incompatible type "Request"; expected "UserViewSet" How can I solve this except ignoring it with type: ignore[]? The probem is that @action decorator in viewset changes the type of method, without it mypy is okay. However @action() ruins it. I need to overcome this, any suggestions? -
Django 3.0 admin searching for different models fields
I faced with some problems with project which I had now... I have different models with included structure (one category can have multiple subcategories) and I want to implement searching by each field which I had in model... now it looks like this code working only for 1st level categories: from django.contrib import admin from .models import * def register_models(models_list): for model, fields in models_list.items(): model_fields = () for field in model._meta.fields: if field.name in fields: model_fields = (field.name, *model_fields) class Admin(admin.ModelAdmin): list_display = ('__str__', *model_fields) list_filter = model_fields search_fields = [*model_fields] admin.site.register(model, Admin) Question, is it possible somehow to implement searching for my structure with many subcategories? I.E if I am in category2 with many subcategories I want to search in category2 subcategory which contains any field with text test -
Django. Increment views count of object without affecting its updated_at field
I have the following model: class Announcement(models.Model): ... created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views = models.PositiveIntegerField(default=0, editable=False) my view: class AnnouncementDetailView(DetailView): model = Announcement context_object_name = 'announcement' template_name = 'web/index.html' def get(self, *args, **kwargs): announcement = get_object_or_404(Announcement, id=kwargs['id']) announcement.views += 1 announcement.save() return super().get(self, *args, **kwargs) The problems are: I know about the F expression, I'll use it down below, but I want to know another ways of updating field and not updating the updated_at field. I want to save the changes of model's views field but everytime I save it, it sets the new value to updated_at field. It means everytime I refresh the page it shows the current time on updated_at field, which is very bad. I have changed my view's code to: ... def get(self, *args, **kwargs): Announcement.objects.filter(id=kwargs['id']).update(views=F('views') + 1) return super().get(self, *args, **kwargs) Now it works fine but I have several questions. How it saves the new value of views field without calling the save method of """"Django"""""? How far can I go with it. What is the best practices of changing some fields of model without hitting the save method? Thanks in advance for broad explanation!