Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to enrich the Django request object with extended functions?
In my Django project, I have a situation where different views communicate via a request session data as follows: def view_one(request): ... request.session['my_session_key'] = data ... def view_two(request): ... data = request.session['my_session_key'] ... However, this has the following problems: The key string my_session_key is not a constant so it will be hard to scale it up to other parts of the code if I start writing to and/or reading from it in other parts of my code. As this system grows, it will become harder to identify which are the available keys being used and written in the session. In Kotlin (which I'm more familiar with), one way to solve this would be using an extension function, like so: var Request.my_session_key: Int get() = this.session['my_session_key'] set(value) { this.session['my_session_key'] = value } This way, I could now write my views as follows: def view_one(request): ... request.my_session_key = data ... def view_two(request): ... data = request.my_session_key ... Is there any way to accomplish something similar in Python or with Django? Or, alternatively, taking a step back, what would be the best way to organize the data stored in a Django session across multiple views? -
Updating partial data in DB while fetching data should count as GET or PUT request in REST API
My class is to fetch current song info from Spotify api. class GetCurrentSong(APIView): def get(self, request): dict_song_info = get_song_from_spotify(user_session=self.request.session.session_key) if 'Error' in dict_song_info: return Response({dict_song_info['Error_Type']: dict_song_info['Error']}, status=dict_song_info['Status']) # Update song name in database try: self.update_song_info_in_db(dict_song_info['name']) except Exception as ex: return Response({'Storage Error': 'Caanot persist current song info to database'}, status=status.HTTP_406_NOT_ACCEPTABLE) return Response(dict_song_info, status=status.HTTP_200_OK) Besides fetching song info and rendering to the frontend, I also need to update song name data in DB before rendering. My question is: this function involves data update (no create new entries, just update existing data record). Does it still count as "Get"? Or actually, I should use "PUT" for this function? -
How can I install Pandas in a Django project that is in a virtual Ubuntu environment
in the virtual machine of ubuntu I have a project in django for production, and within the project I need to install the panda module but it does not let the process be carried out. the following statement pandas collect comes out and then says killed. enter image description here -
Django's form unique_together validation
I want to make an error if a user comments once on a movie and then again on the same movie. Specifically, I want to allow a user to comment on a film only once, and to throw an error if they try to comment twice. How can I change this? Please be specific with your code. class Comment_movie_CreateForm(ModelForm): class Meta: model = Comment_movie fields = ('comment', 'stars') exclude = ['user'] comment = forms.CharField(required=False,label='comment',widget=forms.Textarea( attrs={'placeholder':'example input'}),max_length=1000) stars = forms.FloatField(required=False,label='stars',widget=forms.NumberInput( attrs={'type': 'range','id':'form_homework',"class": "no_resize",'min': '0','max':'10','step':'0.1'})) def clean(self): cleaned_data = super().clean() try: Comment_movie.objects.get(user=self.user, movie=self.movie) except Comment_movie.DoesNotExist: pass else: raise forms.ValidationError('Solution with this Name already exists for this problem') # Always return cleaned_data return cleaned_data class Comment_movie(models.Model): comment = models.TextField(max_length=1000) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ('user', 'movie') indexes = [ models.Index(fields=['user', 'movie']), ] -
How to filter in django with empty fields when using ChoiceField
I have a programme where users should be able to filter different types of technologies by their attributes. My question is, how would I filter the technologies when there's potential conflicts and empty values in the parameters I use to filter? Forms.py: class FilterDataForm(forms.ModelForm): ASSESSMENT = (('', ''),('Yes', 'Yes'),('No', 'No'),) q01_suitability_for_task_x = forms.ChoiceField(label='Is the technology suitable for x?', choices=ASSESSMENT, help_text='Please select yes or no', required=False,) q02_suitability_for_environment_y = forms.ChoiceField(label='Is the technology suitable for environment Y?', choices=ASSESSMENT, help_text='Please select yes or no', required=False) There are many fields in my model like the ones above. views.py class TechListView(ListView): model = MiningTech def get_queryset(self): q1 = self.request.GET.get('q01_suitability_for_task_x', '') q2 = self.request.GET.get('q02_suitability_for_environment_y', '') object_list = MiningTech.objects.filter(q01_suitability_for_task_x=q1).filter( q02_suitability_for_environment_y=q2) return object_list The difficulty is that not all technology db entries will have data. So in my current setup there's times where I will filter out objects that have one attribute but not another. For instance if my db has: pk1: q01_suitability_for_task_x=Yes; q02_suitability_for_environment_y=Yes; pk2: q01_suitability_for_task_x=Yes; q02_suitability_for_environment_y=''; In the form, if I don't select any value for q01_suitability_for_task_x, and select Yes for q02_suitability_for_environment_y, I get nothing back in the queryset because there are no q01_suitability_for_task_x empty fields. Any help would be appreciated. I'm also ok with restructuring everything if … -
I am not using any authentication method to login in Django. I am using this function is it right?
''' def login_action(request): if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: user = Admin_user.objects.get(email_id=request.POST.get('email'), password=request.POST.get('password')) if user!=None: return HttpResponse("Loged IN") else: return HttpResponse("Not a User") ''' this Method Works for me is it a right method. I don't use authenticate method because my models has 5 user type. can any one suggest me a method for 5 user type if my method is not right -
Filtering on annotated field django ORM
I am trying to filter my queryset based on the newly created column using annotation. first_query = Products.objects.annotate(top_rating=Subquery( Ratings.objects.filter(product=OuterRef("pk")) .order_by("-date_val").value('rate_val')[:1], ))) sec_query = first_query.filter(top_rating=4) But I am getting error Cannot resolve keyword 'top_rating' into field -
Django: Getting last value by date from related model in html
Hy all I Just had a question: So on my parent product overview i show the name of the product and it's URL but there is also a related model to that parent model which holds the history of the prices over time. What i want to do is show also the latest price in my table here is my code: models.py: class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100, default=None, null=True, blank=True) url = models.CharField(max_length=255, default=None, null=True, blank=True) creation_date = models.DateTimeField(auto_now_add = True) update_date = models.DateTimeField(auto_now = True) class PriceHistory(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product_info = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) creation_date = models.DateTimeField(auto_now_add = True) My views.py @login_required def overview(request): all_products = PersonalisedTrackingInfo.objects.filter(user=request.user) general_context = {'all_products': all_products} return render(request, 'overview.html', general_context) and my html <h4>Overview Products</h4> <table> <thead> <tr> <th>#</th> <th>Name</th> <th>Url</th> <th>Last price</th> </tr> </thead> <tbody> {% for product in all_products %} <tr> <td>{{ forloop.counter }}</td> <td>{{ product.name }}</td> <td>{{ product.url }}</td> <td>{{ product.id.price}}</td> <td></td> {% endfor %} </tr> </tbody> </table> My question is: how to get the latest price also together with my product in my html overview? I tried with {{ product.id.price}}. I think i'm not far off but can't get my head … -
How to relate models with reverse link
_Hi, guys! How can I relate two models? I want to write like this: user_goal_minutes = ninja.ninjagoal_set.goal_time * 60 My models: class Ninja(models.Model): id_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="ninja", blank=True, null=True) id_teams = models.ManyToManyField("mission.Team", blank=True) avatar = models.ImageField(upload_to='avatar/', default='avatar/default.png', blank=True) goal_time = models.PositiveIntegerField(default=0, blank=True) class NinjaGoal(models.Model): id_mission = models.ForeignKey(Mission, null=True, blank=True, on_delete=models.SET_NULL) id_ninja = models.ForeignKey("accounts.Ninja", null=True, blank=True, on_delete=models.SET_NULL) goal_time = models.PositiveIntegerField(default=0, blank=True) -
Download a file after saving a model in Django
I'm trying to generate a PDF based on a ModelForm using Weasyprint. The idea is when the user clicks save the PDF is generated after the model is saved (I'm using the signal post_save to accomplish this). But when I hit the save button, the model is saved but the download prompt is not shown to the user, even though I have the correct Content-Disposition configuration in my HttpResponse. I also need to pass some parameters to the post_save signal because some of the fields that need to be added to the PDF are not in the Model, but are in the ModelForm, and I have not been able to find out how to do that. admin.py def save_model(self, request: HttpRequest, obj: Contract, form: ContractForm, change: Any) -> None: if not change and not request.user.is_superuser: obj = MythLabsMultiTenancy.assign_organization_to_obj( obj, request.user ) return super().save_model(request, obj, form, change) forms.py from dal.autocomplete import ModelSelect2 from django import forms from django.core.validators import RegexValidator class ContractForm(forms.ModelForm): class Meta: widgets = { 'handover_vehicle': ModelSelect2( url='vehicle_autocomplete', forward=('organization',), ), 'lease_holder': ModelSelect2( url='client_autocomplete', forward=('organization',), ), 'replacement_vehicle': ModelSelect2( url='replacement_vehicle_autocomplete', forward=('organization',), ), } warranty_card_company = forms.CharField(required=False, label='Tarjeta') warranty_card_number = forms.CharField( max_length=19, required=False, label='N° de tarjeta' ) warranty_card_expiration_date = forms.CharField( max_length=5, required=False, … -
How to count and filter object in Django template?
I have two models: in one, the user creates a post, and in the other, the likes of those posts are collected. Now I would like the number of these likes to be displayed on the post. Is there any way for all posts with the number of likes to be displayed on one template? template.html: <div class="col-sm-4 mx-auto "> <ul class="list-group"> {%for post in posts %} <a id="like_{{post.id}}" href="" class="like-link text-muted"> +{% for every_like in likes_obj%}{%if every_like.liked_what == post%}{{every_like.count}}{%endif%}{%endfor%} ## At this point I would like to see the number of likes for each post it is assigned to, but unfortunately {{every_like.count}} returns nothing. </a> {% endfor %} </ul> </div> views.py: def index(request): list = Post.objects.all().order_by('-date') paginator = Paginator(list, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/index.html", { "post_form": PostForm(), "posts": page_obj, "likes_obj": Like.objects.all() }) models.py: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=200, blank=False) content = models.TextField(blank=False) class Like(models.Model): author_of_like = models.ForeignKey(User, on_delete=models.CASCADE) liked_what = models.ForeignKey(Post, on_delete=models.CASCADE) -
To convert m3u8 files directly from a link to mp4 video
I have searched about it and found a python module https://pypi.org/project/m3u8-To-MP4/ but I want a better solution to download video in mp4 format from URL -
Error while makemigrations, relation for custom user
I am currently in the middle of this project and the makemigration command is throwing an error. Previously I used migrated but it worked fine. The error line it is showing was added before and was migrated successfully too. This is the Error E:\Projects\V-conn-API>docker-compose run --rm app sh -c "python manage.py makemigrations base" [+] Running 1/0 - Container v-conn-api-db-1 Running 0.0s Traceback (most recent call last): File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "base_user" does not exist LINE 1: SELECT (1) AS "a" FROM "base_user" WHERE "base_user"."v_id" ... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/py/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/py/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 393, in execute self.check() File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/py/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/py/lib/python3.9/site-packages/django/contrib/auth/checks.py", line 82, in check_user_model if isinstance(cls().is_anonymous, MethodType): File "/py/lib/python3.9/site-packages/django/db/models/base.py", line 477, in __init__ val = field.get_default() File "/py/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 850, in get_default return self._get_default() File "/app/base/models.py", line … -
authenticate return none for custom user model django rest framework
I am trying to use email instead of a username for login in django-rest-framework. but authenticate(request, email=email, password=password) always return None. I tried many ways but always it returns None. can someone help me to solve this problem? Model class CustomUser(BaseUserManager): def create_superuser(self,user_name, email, phone, password,**other_fields): other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_staff', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True') return self.create_user(user_name, email, phone, password, **other_fields) def create_user(self, user_name, email, phone, password, **other_fields): if not email: raise ValueError(gettext_lazy('Email is required')) other_fields.setdefault('is_active', True) email = self.normalize_email(email) user = self.model(user_name=user_name, email=email, phone=phone, **other_fields) user.set_password(password) user.save() return user class Profile(AbstractBaseUser, PermissionsMixin): user_name = models.CharField(unique=True, max_length=255) email = models.EmailField(gettext_lazy('email address'), unique=True) password = models.CharField(null=False, max_length=2000) phone = models.CharField(max_length=30) register_date = models.DateTimeField(default=timezone.now) is_varified = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = CustomUser() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'phone'] serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['email', 'user_name', 'password','phone'] extra_kwargs = { 'password': {'write_only': True} } View class RegisterView(APIView): def post(self, request): serializer = RegisterSerializer(data= request.data) if serializer.is_valid(): serializer.save() email = serializer.data.get('email') password = serializer.data.get('password') user = authenticate(request, email=email, password=password) print(user, email, password) # … -
DJANGO TEMPLATE not grabing image but the image exists
So i have a little problem. I have a funcion to upload and edit news, wich im going to paste the logic here: @login_required def listing_new(request): try: company = Company.objects.get(user=request.user) except Company.DoesNotExist: company = None try: mainnew = MainNew.objects.get(company=company) except MainNew.DoesNotExist: mainnew = '' try: news = New.objects.filter(company=company).order_by('-id')[:3] except New.DoesNotExist: news = None context = { "news": news, "mainnew": mainnew, "company": company, } return render (request, "list_new.html", context) And my template, wich is the one who is working fine: {% extends 'base.html' %} {% load static %} {% block title %} WIZI {% endblock title %} {% block content %} {% if company != None %} {% if mainnew != '' %} <section id="blog" class="blog_area pt-120 pb-130"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-6"> <div class="section_title text-center pb-25"> <h4 class="title wow fadeInUp" data-wow-duration="1.3s" data-wow-delay="0.2s">Notícias</h4> </div> <!-- section title --> </div> </div> <!-- row --> <div class="row"> <div class="col-lg-6"> <div class="single_blog mt-30 wow fadeInUp" data-wow-duration="1.3s" data-wow-delay="0.2s"> <div class="blog_image"> <img src="{{ mainnew.image.url }}" alt="blog" style="height: 450px; width: auto"> </div> <div class="blog_content"> <h3 class="blog_title"><a href="#0">{{ mainnew.title }}</a></h3> <p>{{ mainnew.text }}</p> </div> </div> <!-- single blog --> </div> </div> <!-- row --> </div> <!-- container --> </section> <a href=" {% url 'update-mainnew' %} "><button … -
I need to display statistics as a number
I just started learning django and ran into a problem when using def str(self): return self.timetable the date in the admin panel is displayed as numbers, but it gives the error ''str returned non-string (type datetime.time)'' when replacing str with something else, the time is displayed like this -
Django - what is wrong with my If statement?
Good afternoon all, I inserted an if statement in my template - I only want the form to appear if the product category is "Champagne". For some reason, the product does not appear for champagne products. Here is the code Models.py CATEGORY=( (1,'Rum'), (2,'Gin'), (3,'Whisky'), (4,'Champagne'), (5,'Others'), ) class Product(models.Model): name = models.CharField('Product Name', max_length=120, null=True) category = models.IntegerField(choices=CATEGORY, default=0) description = models.TextField(blank=True, null=True) price = models.DecimalField(null=True, max_digits=6, decimal_places=3) image_url= models.URLField('Image Web Address', blank=True) product_url = models.URLField('Product Web Address', blank=True) class Meta: db_table='Product' def __str__(self): return str(self.name) HTML {% if product.category == 'Champagne' %} <div class="d-flex flex-column mt-4"> <a class="btn btn-outline-secondary btn-sm" href="{% url 'ElderFlowerReview' product.id %}">Tasting Notes</a> </div> {% endif %} Forms.py class DrinkForm(ModelForm): class Meta: model = Product fields = ('name','category', 'description') labels ={ 'name': '', 'category': '', 'description': '', } widgets = { 'name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter name'}), 'category': forms.Select(attrs={'class':'form-control', 'placeholder':'Enter category'}), 'description':forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter description'}), } -
Docker image ran for Django but cannot access dev server url
Working on containerizing my server. I believe I successfully run build, when I run docker-compose my development server appears to run, but when I try to visit the associated dev server URL: http://0.0.0.0:8000/ However, I get a page with the error: This site can’t be reachedThe webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. These are the settings on my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR C:/Users/15512/Desktop/django-project/peerplatform COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . ./ EXPOSE 8000 CMD ["python", "./manage.py", "runserver", "0.0.0.0:8000", "--settings=signup.settings"] This is my docker-compose.yml file: version: "3.8" services: redis: restart: always image: redis:latest ports: - "49153:6379" pairprogramming_be: restart: always depends_on: - redis command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" env_file: - ./signup/.env - ./payments/.env - ./.env build: context: ./ dockerfile: Dockerfile ports: - "8000:8001" container_name: "pairprogramming_be" volumes: - "C:/Users/15512/Desktop/django-project/peerplatform://pairprogramming_be" working_dir: "/C:/Users/15512/Desktop/django-project/peerplatform" This is the .env file: DEBUG=1 DJANGO_ALLOWED_HOSTS=0.0.0.0 FYI: the redis image runs successfully. This is what I have tried: I tried changing the allowed hosts to localhost and 127.0.0.0.1 I tried running the command python manage.py runserver and eventually added 0.0.0.0:8000 When I run … -
How to create a modelform and save object in Django?
all! models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class UserChoice(models.Model): user_choice = models.ForeignKey(Choice, on_delete=models.CASCADE) def __str__(self): return self.user_choice views.py: def index(request): question_list = Question.objects.all() context = {'question_list': question_list} return render(request, 'polls/index.html', context) index.html.py: <form method="post""> {% csrf_token %} {% for question in question_list %} <h3>{{question.question_text}}</h3> <select hidden="" name="form-{{ forloop.counter0 }}-question" id="id_form-{{ forloop.counter0 }}-question"> <option value="{{question.id}}" selected="">{{question.question_text}}</option> </select> {% for answer in question.choice_set.all %} <label for="id_form-{{ forloop.counter0 }}-answer"> <input type="radio" name="form-{{ forloop.parentloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer" value="{{answer.id}}"> {{answer.choice_text}} </label> <br> {% endfor %} {% endfor %} <br /> <br /> <input type="submit" value="Submit"> </form> Question: How to save user choice using UserChoice model per each question? How to create such modelform? Is my UserChoice model is good for storing these informations? P.s. I know how to create simple ModelForm, but here my little knowledge about Django stopped me :). For now, I have no idea how to create this form, I read about modelformset_factory, but did not understand...( Any help appreciated! -
I'm trying to send email with Django
I'm trying to send email with Django but i keep getting SMTPConnectError ErrorMessage [Views.pysettings.py -
Placement of {% if form.errors %} on login template
I'm not sure if I'm allowed to ask these types of questions here since it's not a problem per say, so please let me know. But I was wondering for the login.html template on Django: {% extends 'learning_logs/base.html' %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method = "post" action="{% url 'login' %}"> {% csrf_token %} {{ form.as_p }} <button name = "submit">log in</button> <input type="hidden" name="next" value="{% url 'learning_logs:index' %}" /> </form> {% endblock content %} How come it checks for the form.errors before the it even processes the form? Thanks for any help on this question. -
Django APITest case not returning anything in get request
I am developing an API with Django, and I also want to test it, but I am having some trouble doing that. I need to test that to a given URL, what is returned is what I expect, and I want to do so with APITestCase of django rest framework. The endpoint is something similar: http://localhost:5000/api/v1/rest_of_url/ When I type it in the browser, it return something similar: {"count": 1, "next": null, "previous": null, "results": [{"stuff": 3, "stuff2": "adf", "stuff3": "asdf", "stuff4": "ff"}]} So, to test that I wrote the following code in Django: class TargetApiTestCase(APITestCase): def test_get(self): response = self.client.get("/api/v1/rest_of_url/", format='json') print(response) print(response.content) print(response.status_code == status.HTTP_200_OK) As response I get the following output from the prints statements: <JsonResponse status_code=200, "application/json"> b'null' True But I should get some data, to check. I know that after that I have to query the db to check and use self.assertEqual, but for now my problem is retrieving data via get Maybe it is only a problem of settings. I tried require responde.data, but it responded with an error. Please, can someone help me? Thank -
How to check if a object has ManyToMany reference in a queryset django?
I have these models in my django project class Question(models.Model): heading = models.CharField(max_length=300) description = models.TextField() class Profile(models.Model): name = models.CharField(max_length=100,null=False,blank=False) completed = models.ManyToManyField(Question) I'm trying to find a optimized way for fetching a list of questions for user it should with whether they have completed it or not. I think it can be done with these quersets:- all_questions = Question.objects.all() completed_questions = Question.objects.filter(profile = profile_instance) where profile_instance is a profile object. Then we can loop through the all_questions and check whether they also exist in completed_questions, but i am not sure whether this is optimized for pagination. I'm using Django-Rest Framework pagination. -
How to write changes in fields to LogEntry?
I had a task to create action which will change status of object(s). Action is already create. Code for example: class MyAdmin(admin.ModelAdmin): actions = ['decline_status', ] def decline_status(self, request, queryset): decline_status = constants.DECLINED.value objects_to_decline = queryset.exclude(status=decline_status).filter(status=decline_status) if objects_to_decline.count() > 0: objects_to_decline.update(status=decline_status) But now I have a problem: I need to write changes which were called by decline_status action to LogEntry table. Nothing is happend when i use LogEntry.objects.create(different_kwargs). And I'm trying to use self.log_change(request, obj, some_change_message), but changes appear only on the main page of admin in the window: recent actions window I need to write changes to LogEntry like they are written after default action delete_selected. Can you help me? -
How to update M2M field related data attributes in Django
I want to update the vote value of each candidate which is related with m2m field of specific Constituencies. I have Constituencies update function where user update the Constituencies but i my case i also want to update the candidates vote value which is coming from object in object.candidates.all class Candidates(models.Model): name = models.CharField(max_length=100) votes = models.PositiveBigIntegerField(default=0) class Constituencies(models.Model): candidates = models.ManyToManyField(Candidates) views.py def constituency_detail(request, pk): obj = get_object_or_404(Constituencies, id=pk) form = ConstituenciesForm(request.POST or None, instance=obj) if request.method == 'POST': pass template.html <h5>{{ object }}</h5> {% for object in object.candidates.all %} <h5>{{ object }}</h5> {{ object.votes }} as input field {% endfor %}