Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - customized ModelAdmin to show ManyToMany filtered view (vetical or horizontal) by related fields filters
I have a Model with a field: class SampleModel(models.Model): questions = models.ManyToManyField('questions.Question') 'Question' objects do have some simple foreign keys like Department or Organisation (with their corresponding 'name' fields). Could somebody point me a direction how to achieve the following: i'd like to have in Admin of "SampleModel" a way to filter these questions list by their related fields (department, organisation). I've seen some examples that should work for simple foreign keys, but nothing works for ManyToMany. Is there eventually any addon with similar funcionality? -
Psycopg2 installation error on mac: command 'clang' failed with status 1
I can't install psycopg2 on my m1 Mac. I tried to reinstall openssl with brew. I tried a lot of thing but nothing changed. The error log is super long so I couldn't understand what is wrong. I am facing up with this error when I try to pip install psycopg2 Waiting for your help. Here is the full error log: https://wtools.io/paste-code/b4jG -
Geodjango | 'DatabaseOperations' object has no attribute 'geo_db_type'
I am building a BlogApp . AND I am stuck on an Error. What i am trying to do I am making a Location Based BlogApp and I am using PointField in models. The Problem 'DatabaseOperations' object has no attribute 'geo_db_type' This error is keep showing when i migrate. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '---------', 'HOST': 'localhost', 'PORT': '', } } What have i tried I also tried chaning 'django.db.backends.postgresql_psycopg2' to 'django.contrib.gis.db.backends.postgis'. BUT it is showing django.db.utils.OperationalError: could not open extension control file "C:/Files/PostgreSQL/13/share/extension/postgis.control": No such file or directory I also tried many answers but nothing worked for me. I have installed pip install psycopg2. -
% being appended to existing % in django template
I am developing a django based web application. I use django templates in html. There is a form containing textbox where i enter a value with % symbol But i notice that the post request converts the text box value to this format below txtBillingAccName=Billing+Account+25%25 Due to this the values get saved in the database like this: I need to use % symbol for most of the Billing Account Names. Can anyone please help me,how to solve this?. Thanks -
No route found for path in Django-channels
Using django channels im trying to connect to a websocket but it can't find it. I tried to see if its because of routing.py or consumer.py and i can't find the answer. I get the warning that no route was found for path 'tribechat/1/'. git error message: Traceback (most recent call last): File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\security\websocket.py", line 37, in __call__ return await self.application(scope, send, receive) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 168, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'tribe_chat/1/'. Console error message: WebSocket connection to 'ws://127.0.0.1:8000/tribe_chat/1/' failed: routing.py: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.urls import path, re_path from tribe_chat.consumers import TribeChatConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ re_path(r'ws/tribe_chat/(?P<room_id>\w+)/$', TribeChatConsumer.as_asgi()), ]) ) ), }) consumers.py: from channels.generic.websocket import … -
Django, get value from url after "#"
I have a callback endpoint in my Django app And on this callback endpoint comes such request http://127.0.0.1:8000/callback/#state=cc444d19-bd8c-4b4c-8011-1054fd0e8e73&session_state=8776a4ca-033b-469e-8a50-81f90c81c5ef&code=7ade58cf-d6ed-4c20-8d8c-33453c37c44e.8776a4ca-033b-469e-8a50-81f90c81c5ef.913199c3-a793-4f5a-ac36-b4c105a08000 How can I get values that comes after "#"? -
Can't upload files larger than 2mb from Angular to Django rest framework
I want to be able to upload audio files of any size from an Angular website to Django backend. At the moment i am able to upload small files up to ~2mb without any problems, however, when uploading files larger than 2mb the Django function that handles the file upload doesn't fire, and no errors occur in Angular frontend. Angular uploadFile() { this.subscription = this.ApiService.uploadfile(this.fileToUpload,this.myControl.value).subscribe(data => { this.UtilsService.openSnackBar('Successfully added wavs',this.myControl.value) // do something, if upload success alert("success") }, error => { //console.log(error); alert("error") }); this.dialogRef.close(); } Upload function of ApiService, sends some parameters along with file(s) uploadfile(file,inst_label):Observable<any>{ const formData: FormData = new FormData(); for(let i = 0; i < file.length; i++){ if(i==0){ formData.append(inst_label,file[i],file[i].name) } else{ formData.append(i.toString(),file[i],file[i].name) } } return this.http.post(this.baseurl + '/upload_files', formData); } On my settings.py i have set: FILE_UPLOAD_MAX_MEMORY_SIZE = 5000000000 # 50 MB DATA_UPLOAD_MAX_MEMORY_SIZE = 5000000000 # 50 MB FILE_UPLOAD_PERMISSIONS = 0o644 Lastly my function upload_files in views.py prints something when files are less than 2mb, if the files are >2mb nothing happens. Hope i was clear enough, i'm running out of ideas on what to do besides cut those large files to smaller ones before uploading. -
Setting Default Image Dynamically Based On Model Choice - Django
Say I have a class: imageModel(models.Model): O1 = 'Option1' O2 = 'Option2' CHOICES = ( (O1, 'Option1'), (O2, 'Option2'), ) options = models.CharField(max_length=50, choices=CHOICES) image = models.ImageField() How would I dynamically set the default for the image field based on the option choice? I tried something like: imageModel(models.Model): O1 = 'Option1' O2 = 'Option2' CHOICES = ( (O1, 'Option1'), (O2, 'Option2'), ) options = models.CharField(max_length=50, choices=CHOICES) image = models.ImageField() def get_default_image(self): super().save() img = Image.open(self.company_logo.path) if self.options == "Option1": img.default = "/static/img/option1img.jpg" elif self.options == "Option2": img.default = "/static/img/option2img.jpg" img.save(self.image.path) But that didn't work. -
Send api request every x minutes and update context with status
I am trying to make a website, where user can start a task on a button click, which will send an api request every x seconds/minutes. Api request gets a list of offers as a response and the task will check if the api request is the same as before. If it is then then i want to show status on my page as: "No offers were found, still searching" and if the api response is different the status changes to: "I found an offer" I wanted to make that process in the background and without need to refresh the page by user. I want the context["status"] to be automatically updated when new offer is found. I tried to achieve this with threading but the page keep on loading as a task is working. Every idea is appreciated. Thanks! -
I can't browse server files with Django Ckeditor
I build a django application. I use DigitalOcean space to store my media files. I use Django Ckeditor to allow admin to write content with nice textarea and to allow them to upload some images. Uploading image is working (in the folder : "modules_images" as you can see in my code). Problem happen's when admin want to click on the button "browse server". He get the following error : NoSuchKey at /ckeditor/browse/ An error occurred (NoSuchKey) when calling the ListObjects operation: Unknown I spent a lot of time looking for people who already meet this problem but no one had exactly the same (people who meet problems at browsing files generally meet problems at uploading files too) and no one of the answers helped me. Here is my urls.py : urlpatterns = [ ... path('admin/', admin.site.urls, name="admin"), path('chaining/', include('smart_selects.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is my ckeditor configs in settings.py : CKEDITOR_UPLOAD_PATH = "modules_images/" CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', # 'skin': 'office2013', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']}, {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']}, {'name': 'editing', 'items': … -
Django admin queryset foreign key to user
I have an e-commerce development and I'm looking to send an email to the client from the admin site, I can´t the queryset correclty to do this. I have the following model: models.py class Orden(models.Model): cliente = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name='Usuario') productos = models.ManyToManyField(OrdenProducto) fecha_orden = models.DateTimeField(auto_now_add=True) completada = models.BooleanField(default=False, null=True, blank=True) id_transaccion = models.CharField(max_length=20, null=True) correo_enviado = models.BooleanField(default=False, null=True, blank=True) datos_pedido = models.ForeignKey( 'DatosPedido', on_delete=models.SET_NULL, blank=True, null=True) pago = models.ForeignKey( 'Pago', on_delete=models.SET_NULL, blank=True, null=True) cupon = models.ForeignKey( 'Cupon', on_delete=models.SET_NULL, blank=True, null=True) class Meta: verbose_name_plural = "Orden" def __str__(self): return self.cliente.username 'cliente' has a foreign key to the 'User' model and I want to get the email address, I have tried many ways but I just can´t get it admin.py class OrdenAdmin(admin.ModelAdmin): list_display = ('cliente', 'completada', 'correo_enviado') actions = ['enviar_correo'] def enviar_correo(self, request, queryset): queryset.update(correo_enviado=True) a = queryset.get(cliente=self.user.email) send_mail('test', 'test', 'xxxxxx@mail.com', ['a], fail_silently=True) -
How to add a pre-defined formlist and condition dict to a Sessionwizard (Django 2.2)?
I've implemented the accepted answer with make_condition_stuff function in this Stackoverflow post for repeating a Django SessionWizard step as long as the button 'add another' is pressed, or True, which works. I want to add this function for one wizard step, more specifically, wizard step 3. The make_condition_stuff function returns an own form list and a condition dict that I want to add to the wizard form list and condition dict for the other steps. I'm not sure how to add or update the condition dict and form list in the wizard with the external condition dict and form list from the function make_condition_stuff. How can I integrate the external form_list and condition dict from the function with the ordinary wizard form list and condition dict ? I've tried to define a condition dict and form_list in the wizard self init and passed it to the method get_form_list but it raises an error with the Ordered dict that the ordinary wizard form_list is based on whereas the returned form_list from the function is an ordinary list but a Type error is raised when I try to append the function form_list to the Ordered dict with the wizard form_list. I've found … -
How to do a multi-value filter in Django?
I have the following code: class PageListView(generics.ListAPIView): queryset = Page.objects.all() serializer_class = PageSerializer filter_backends = (filters.DjangoFilterBackend, OrderingFilter) filter_fields = ('category', 'calculated_hsk') pagination_class = LimitOffsetPagination ordering_fields = ['date'] My category value is an integer. I am calling my local API as such: http://127.0.0.1:8000/api/v1/pages/?category=1,6&calculated_hsk__in=4.00&limit=10&ordering=-date&offset=0 However this does not work I have also tried http://127.0.0.1:8000/api/v1/pages/?category__in=1,6&calculated_hsk__in=4.00&limit=10&ordering=-date&offset=0 Which likewise doesn't work. Is there a specific filter backend I need? I am trying to replicate this aspect of a query: WHERE category IN (value1, value2, ...) -
How do I combine my Django models so that I am not repeating myself?
I realize that the 3 models that I use right now have a ton of shared fields. I was wondering what the best way to condense these models would be. I've read some articles on metaclasses and model inheritance but wanted to see what the "best" way to do this would be. models.py class Car(models.Model): created = models.DateTimeField(auto_now_add=True) make = models.CharField(max_length=100) model = models.CharField(max_length=100) year = models.IntegerField(default=2021, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)]) seats = models.PositiveSmallIntegerField() color = models.CharField(max_length=100) VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)]) current_mileage = models.PositiveSmallIntegerField() service_interval = models.CharField(max_length=50) next_service = models.CharField(max_length=50) class Truck(models.Model): created = models.DateTimeField(auto_now_add=True) make = models.CharField(max_length=100) model = models.CharField(max_length=100) year = models.IntegerField(default=datetime.now().year, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)]) seats = models.PositiveSmallIntegerField() bed_length = models.CharField(max_length=100) color = models.CharField(max_length=100) VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)]) current_mileage = models.PositiveSmallIntegerField() service_interval = models.CharField(max_length=50) next_service = models.CharField(max_length=50) class Boat(models.Model): created = models.DateTimeField(auto_now_add=True) make = models.CharField(max_length=100) model = models.CharField(max_length=100) year = models.PositiveSmallIntegerField(default=datetime.now().year, validators=[MaxValueValidator(datetime.now().year)]) length = models.CharField(max_length=100) width = models.CharField(max_length=100) HIN = models.CharField(max_length=14, validators=[MinLengthValidator(12)], blank=True) current_hours = models.PositiveSmallIntegerField() service_interval = models.CharField(max_length=50) next_service = models.CharField(max_length=50) -
ImportError: Couldn't import Django. Problem with deploying Django app to Heroku
I'm trying to deploy my Django app to Heroku but I keep having this error after successfully building the app. This is the log after a successful build: 2021-03-16T15:21:32.000000+00:00 app[api]: Build succeeded 2021-03-16T15:21:32.647557+00:00 heroku[web.1]: State changed from crashed to starting 2021-03-16T15:21:36.820238+00:00 heroku[web.1]: Starting process with command `python manage.py runserver 0.0.0.0:49625` 2021-03-16T15:21:39.146005+00:00 app[web.1]: Traceback (most recent call last): 2021-03-16T15:21:39.146029+00:00 app[web.1]: File "manage.py", line 11, in main 2021-03-16T15:21:39.146029+00:00 app[web.1]: from django.core.management import execute_from_command_line 2021-03-16T15:21:39.146030+00:00 app[web.1]: ModuleNotFoundError: No module named 'django' 2021-03-16T15:21:39.146030+00:00 app[web.1]: 2021-03-16T15:21:39.146031+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2021-03-16T15:21:39.146031+00:00 app[web.1]: 2021-03-16T15:21:39.146031+00:00 app[web.1]: Traceback (most recent call last): 2021-03-16T15:21:39.146032+00:00 app[web.1]: File "manage.py", line 22, in <module> 2021-03-16T15:21:39.146032+00:00 app[web.1]: main() 2021-03-16T15:21:39.146032+00:00 app[web.1]: File "manage.py", line 13, in main 2021-03-16T15:21:39.146033+00:00 app[web.1]: raise ImportError( 2021-03-16T15:21:39.146046+00:00 app[web.1]: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? 2021-03-16T15:21:39.193415+00:00 heroku[web.1]: Process exited with status 1 2021-03-16T15:21:39.280185+00:00 heroku[web.1]: State changed from starting to crashed 2021-03-16T15:22:38.622544+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=metamedapp.herokuapp.com request_id=1fccc50d-d117-4cab-862c-91d05b765c4d fwd="86.7.108.29" dyno= connect= service= status=503 bytes= protocol=https 2021-03-16T15:22:39.701300+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=metamedapp.herokuapp.com request_id=723d001f-0cf6-4291-b884-e5d7772d9d3c fwd="86.7.108.29" dyno= connect= service= status=503 bytes= protocol=https … -
What is the expected behaviour when a model has two foreign keys with different on_delete constraints?
Let's say I have this model: class UserBook(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) book = models.ForeignKey(Book, on_delete=models.PROTECT) Where the user is only allowed to borrow 1 book at a time. I want instances of this model to get deleted if the user gets deleted, but I don't want them to get deleted if a book gets deleted (by mistake, just a precaution). What is the expected behaviour when a user gets deleted using the above constraint? I'm getting: Cannot delete some instances of model 'UserBook' because they are referenced through a protected foreign key Is there a way to achieve what I want? I tried to delete UserBook on pre_save/post_save signals but neither worked. -
Is there Django form field or widget that appends Radio and CharField
I'm trying to create a Django form fields that has radio choices and "other" choice that is a text field. It should look like this I tried this but its from 2014 and it's not working. Can you give me an idea how to fix this code or how can I create a custom widget that will do the job. Thank you for your help! -
Python replace multiple substrings in a string
I have a text: "{name} likes {post}". I fetch data according to the values inside {} from db. Then I get values coming inside an Array, like ["John", "515335"] for one piece of data. I don't know how many variables I will get inside the string. Would be 1 or 3 too. ( But the count of content to be replaced and values will be same) So what would be the best way to replace the values in this string please? Expected output: "John likes 515335" -
Django and PostgreSQL - how to store time range?
I would like to store a time range (without dates) like "HH:MM-HH:MM". Can you give me a hint, how can I implement it most easily? Maybe there is a way to use DateRangeField for this aim or something else. Thanks for your spend time! -
Print a html page using django
I want to print a HTML page using django. I mean that if an user wants to print a webpage with printer when press print button 《print button is a HTML button with tag 》 server automatically print that webpage on a paper. Thanks. -
Django how to access a radio buttons selected value
I'm a little bit rusty on Django and require some basic assistance. I am creating a quiz application and I have correctly displayed all questions and answers of that question. I am using a radio button and upon the user clicking submit, I need to access the answer that was selected to calculate the result. I am having trouble accessing the answers submitted by the user. I think I need to create an HTML form to do that and access it in the views but as I have multiple questions in the same page I am confused. Here is a snippet of where I need the assistance: sampleConfirmation.html {% extends 'home.html' %} {% load crispy_forms_tags %} {% block content %} <div id="questionForm" class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend id="headerForm" class="border-bottom mb-4">Complete your sample quiz! This will generate your level!</legend> {{ form|crispy }} </fieldset> </form> <div id ="displayQuestions" class="question-section"> {% for q in questions %} <table> <tr> <td> {{q.question}}</td> </tr> <fieldset id = "group1"> {% for a in answers %} {% if a.answerForQuestion == q%} <tr> <td> <input type="radio" name = "{{q.id}}" value="{{q.id}}"> {{a.answer}}</td> {{q.id}} </tr> {% endif %} {% endfor %} </fieldset> </table> {% endfor %} </div> … -
Get current path in custom django search_form admin template
I have a custom search_form.html template for my AdminModel template, i want get current url path for make a conditional render of a button but {{ request.path }} dont return nothing, settings.py (TEMPLATES list): TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] directories structure: IMAGE search_form.html template: IMAGE result (BLANK): IMAGE -
django.db.utils.OperationalError: no such table: contacts_contact
I am trying to migrate to migrate my database using python manage.py makemigrations and manage.py migrate but always getting this error django.db.utils.OperationalError: no such table: here is the full traceback. python manage.py migrate Traceback (most recent call last): File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: contacts_contact The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, … -
Can't see modification of model fields in admin panel
Get this issue short time after deploy on server (engine x + g unicorn + django3.0 + sqlite3): Added some field in models file -> added this field in fields list Admin class (admin file) -> manage make migrations -> manage migrate, so i get the message of successful migration...but then i see no scheme changes in admin panel. Database is modified and i don't have this problem on local test server. models file: from django.db import models from django.utils import timezone class AdultCatCard(models.Model): name = models.CharField(max_length=20, verbose_name='Name') testfield = models.CharField(null=True, blank=True, max_length=50, verbose_name='testfield') admin file: from django.contrib import admin from .models import AdultCatCard from django.utils.safestring import mark_safe class CatCardAdmin(admin.ModelAdmin): fields = ['name', 'testfield'] admin.site.register(AdultCatCard, CatCardAdmin) -
I am having a problem with my like button, from question earlier. Noting is still happening to my page
I manage to put my like button on my user profile page. But when I click on it it doesn't return anything. It supposes to show count() - like butten. Which I add to my view.py file. models.py class CustomKorisnici(AbstractUser): MAJSTOR = '1' KORISNIK = '2' USER_TYPE_CHOICE = ( (MAJSTOR, 'majstor'), (KORISNIK, 'korisnik') ) user_type = models.CharField(max_length=100,blank=True,choices=USER_TYPE_CHOICE) username = models.CharField(max_length=100,unique=True) ... def __str__(self): return self.username + ' | ' +self.last_name + ' | ' + self.first_name + ' | ' + str(self.phone_number) + ' | ' + self.user_type + ' | ' + self.email+ ' | ' + str(self.id) class LikeButton(models.Model): user = models.ForeignKey(CustomKorisnici, on_delete=models.CASCADE) likes = models.ManyToManyField(CustomKorisnici,related_name='profile_like') def total_likes(self): return self.likes.count() view.py def LikeProfile(request,pk): like = get_object_or_404(LikeButton, id=request.POST.get('majstori_id')) like.likes.add(request.user) return HttpResponseRedirect(reverse('majstori_profile', args=[str(pk)])) class LikeMajstoriProfile(DetailView): model = LikeButton context_object_name = 'like_button' template_name = 'majstori_profile.html' def get_context_data(self, *args, **kwargs): context = super(LikeMajstoriProfile, self).get_context_data(*args, **kwargs) stuff= get_object_or_404(LikeButton, id=self.kwargs['pk']) total_likes = stuff.total_likes() context['total_likes'] = total_likes return context class MajstoriProfile(DetailView): model = CustomKorisnici context_object_name = 'majstori' template_name = 'majstori_profile.html' def get_context_data(self, *args, **kwargs): context = super(MajstoriProfile, self).get_context_data(*args, **kwargs) majstori= get_object_or_404(CustomKorisnici, id=self.kwargs['pk']) context['majstori'] = majstori return context urls.py path('ProfileMajstori/<int:pk>/', LikeMajstoriProfile.as_view(), name="majstori_like"), html.page <div> <div> <form action="{% url 'like_majstor' majstori.pk %}" method="post"> {% csrf_token %} <button …