Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nested Serializers in Django Rest API - getting parents elements and parents of a parents
I have a self-referencing model (which represents category, it's parents and children): class Category(models.Model): name = models.CharField(max_length=200, unique=True) parent = models.ForeignKey("self", on_delete=models.CASCADE, related_name='children', null=True, blank=True) def __str__(self): return self.name What I am trying to do is creating an api, which would return requested elements: Children, Parents and Their parents (only 2 level of parent elements without infinite recursion). These are the Serializers I wrote: lass ChildrenSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name') class ParentSerializer(serializers.ModelSerializer): """Recursively retrieving all of the parents""" parent = serializers.SerializerMethodField() class Meta: model = Category fields = ('id', 'name', "parent") def get_parent(self, obj): if obj.parent is not None: return ParentSerializer(obj.parent).data else: return None class CategorySerializer(serializers.ModelSerializer): parent = ParentSerializer(required=False) children = ChildrenSerializer(many=True, required=False) class Meta: model = Category fields = ('id', 'name', 'parent', 'children') 1. The problem is that right now it returns element's parents recursively (parents, their parent etc.), while i need to go only 2 level above and return element's parent and parent's parent. How do I do that? 2. Also, right now it return parents like this: { "id": 5, "name": "1.1.1.1", "parent": { "id": 3, "name": "1.1.1", "parent": { "id": 2, "name": "1.1", "parent": { "id": 1, "name": "1", "parent": null … -
Form created in Javascript function disappears when submit is pressed
Right now I am creating a webpage for a Django-based web application. On this page there is a form which is Django generated. The form submission is done by Javascript and makes an AJAX call to get some data from the server. That data is used to created another form. When this form is submitted the page reloads and the form dissappears. I also lose my console data for figuring out what the javascript is doing on the submission of the form. It is working in some sense though because I get '"POST /map/ajax/submit_table HTTP/1.1" 200 3' on the server which corresponds to the correct AJAX call for the second form. Below is the code that generates the second form. Again it is in the Javascript that deals with a successful AJAX response to the submission of the first form. $("#select_table").submit( function(e) { e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ type: 'POST', url: "/map/ajax/get_table", data: serializedData, success: function (response) { table = response["table"]; col_types = response["col_types"]; var f = document.createElement("form"); f.setAttribute('id',"table_form"); for ( const property in col_types) { var i = document.createElement("input"); var l = document.createElement("label"); i.setAttribute('type',"text"); l.innerHTML = property; value = col_types[property]; i.setAttribute('class',value); l.appendChild(i); f.appendChild(l); } var s = document.createElement("input"); … -
How to make a foreign key relationship to a many-to-many field?
I have the following models: class Work_Music(MPTTModel, Work): name = models.CharField(max_length=10, null=True, blank=True) class Cast(models.Model): name = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.name class WorkCast(models.Model): work = models.ForeignKey(Work_Music, verbose_name=_('work'), related_name='workcast', null=True, blank=True, on_delete=models.PROTECT) cast = models.ManyToManyField(Cast, verbose_name=_('cast'), related_name='workcast', blank=True) def __str__(self): return "%s" % ( ", ".join(character.name for character in self.cast.all()) ) Currently the data structure is: WorkCast |-----> Opera |-----> Opera cast member #1 Opera cast member #2 Opera cast member #3 I would now like to attach a sing range to each cast member for this particular piece of work. Some thing like: WorkCast |-----> (ForeignKey) Opera |-----> (Many-to-many) Opera cast member #1, lowest note: c, highest note: A# Opera cast member #2, lowest note: b, highest note: D Opera cast member #3, lowest note: a, highest note: E How can I attached: lowest_note = models.CharField(max_length=10, null=True, blank=True) highest_note = models.CharField(max_length=10, null=True, blank=True) for each cast member for this particular piece? -
How do I send data along with a `client.patch()` using APITestCase in DjangoRestFramework?
My TestCase: class MyApiTests(APITestCase): def test_retrieve(self): resp = self.client.patch('/my/endpoint/', data={ 'name': 'new name', 'age': 25, 'some_array': [{ 'my_subobject_name': 'foo' }] } In my viewset, if I grab data['some_array'], I get: u"{'my_subobject_name': 'foo'}". Why is it a string instead of an array with one dictionary? If I send a stringified version of { 'name': 'new name', 'age': 25, 'some_array': [{ 'my_subobject_name': 'foo' }] } via my browser, DRF works fine, and some_array will be a an array with one dictionary inside of it, as expected. What is the correct way to send a complex data structure along with a patch() in an APITestCase unit test? -
How can I use Django inline formset with Bootstrap-select plugin?
I've been trying to use the Django inline formset with the bootstrap-select plugin from here https://developer.snapappointments.com/bootstrap-select/ and every other thing works perfectly, I'm able to successfully call the plugin on another two selects that I have in my form and I'm using the inline formset to add new authors on my book. When i put the "selectpicker" class, it only works once, when the page is loaded, but when I press the button to add more authors, the select field is not loaded. So I have a question... can I use the two together? If yes, how? If not, is there any workaround to be able to search in a selection field? Bellow is a image to how my form looks when i press the big green "Add" button at the end of the form. You can see that there is only two fields, one less than the first one. If any code is needed, please let me know and i will add right away. Thanks! -
Generate a numbers starting from 1 and increasing until the end of the year, then repeat in the next year
I have a model named 'post' , and I want this model to have a field named "id_field" which will take automatic value start from 1 and increasing with every post saved until the end of the year, then start again from 1 in the next year and so on. for example in 2020: post_1 --> id_field = 1 post_2 --> id_field = 2 post_3 --> id_field = 3 . . . post_n --> id_field = n then when 2021 came: post_n+1 --> id_field = 1 post_n+2 --> id_field = 2 post_n+3 --> id_field = 3 Sorry for my bad english and I hope I explained the problem correctly, thanks. -
Django test issue with dynamically created home page
Problem I'm attempting to create an app that allows for editable home/about pages using a very simple database model but am running into issues when attempting to test the most basic page responses. The issue lies within the use of self.response = self.client.get(reverse('home')) in the setUp method of the test but I'm new to Django and MVC design and can't quite figure out what the underlying issue is. Model class Page(models.Model): title = models.CharField(max_length=50) content = models.TextField() View class HomePageView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['home'] = Page.objects.get(pk=1) return context URLs urlpatterns = [ path('', HomePageView.as_view(), name='home'), ] Test class HomepageTests(TestCase): def setUp(self): home = Page.objects.create(title='Home', content='foo bar') home.save() self.response = self.client.get(reverse('home')) def test_homepage_status_code(self): self.assertEqual(self.response.status_code, 200) def test_homepage_template(self): self.assertTemplateUsed(self.response, 'home.html') Test result ====================================================================== ERROR: test_homepage_template (pages.tests.HomepageTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/code/pages/tests.py", line 12, in setUp self.response = self.client.get(reverse('home')) ... pages.models.Page.DoesNotExist: Page matching query does not exist. ---------------------------------------------------------------------- Initially it seemed like the issue was the lack of a pk=1 object in the test database, but the issue persisted after adding a test page. -
How to search image on google using python and get results page as output
I am working on a project and not able to integrate MRISA as it is based on flask so kindly an alternative to it in Django or as a python script -
Django: How to do an override of fields based on it's value in an aggregation query (join on multiple columns)
I have been looking for a while on different corners of the internet and the Django Project documentation without success so here my question: As background I'm synchronizing the models with an external API so I would prefer not to have to change the model structure. I have the following Models (just left the relevant fields for brevity): TimeEntry: class TimeEntry(models.Model): id = CharField(primary_key=True, max_length=255) duration_decimal = DecimalField(max_digits=5, decimal_places=2, verbose_name='dec duration') start = DateTimeField() project = ForeignKey(Project, models.SET_NULL, blank=True, null=True) user = ForeignKey(User, models.SET_NULL, blank=True, null=True) Membership class Membership(models.Model): user = ForeignKey(User, models.SET_NULL, blank=True, null=True) project = ForeignKey(Project, models.SET_NULL, blank=True, null=True) hourly_rate = ForeignKey(HourlyRate, models.SET_NULL, blank=True, null=True) active = BooleanField(default=True) User class User(models.Model): hourly_rate = DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) HourlyRate class HourlyRate(models.Model): amount = MoneyField(max_digits=10, decimal_places=2, blank=True, null=True, default_currency='USD') The hourly rate can be set at the user level and it can be overridden at the membership level, so I'm trying to create a Django-ORM query to get the value of the overridden hourly rate or the user hourly in case the value at the membership level is not defined and multiply it by the decimal duration and then aggregate everything per month to generate a reporting of hours consumed … -
Openapi 3 with Django drf
I am using Django with Django-Drf to write a restful BE. I am also using drf-yasg to generate the swagger scheme for my service. Unfortunately, drf-yasg does not yet support OpenApi3, and it doesn't look like it's going to in the foreseeable future. Is there an alternative to drf-yasg, that does support Openapi 3 I can use together with Django-Drf? -
SMTPSenderRefused when access to less secure apps on gmail is turned on
I am getting this error: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError o187sm3117216qkf.26 - gsmtp',...) I have access to less secure apps turned on, but I still get this error. Does anyone know other ways of fixing this issue? Thanks -
pysolr.SolrError: Solr responded with an error (HTTP 400): [Reason: undefined field status]
I am using pysolr 3.8.1,django-haystack 2.8.1 and i installed solr version 8.3.1 on ubuntu 18. When I ran my django 2.2 project, in python 3.6.9 I am getting below error. I would like to know why? does it have to do with a version of solr? if search_engine == 'whoosh': haystack_conn = { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'), } elif search_engine == 'solr': haystack_conn = { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://127.0.0.1:8983/solr/bsd', } elif search_engine == 'elastic_search': haystack_conn = { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'arts', } HAYSTACK_CONNECTIONS = { 'default': haystack_conn, } Failed to query Solr using '((android) AND status:(approved))': Solr responded with an error (HTTP 400): [Reason: undefined field status] Traceback (most recent call last): File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/haystack/backends/solr_backend.py", line 138, in search raw_results = self.conn.search(query_string, **search_kwargs) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/pysolr.py", line 742, in search response = self._select(params, handler=search_handler) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/pysolr.py", line 437, in _select return self._send_request('get', path) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/pysolr.py", line 412, in _send_request raise SolrError(error_message % (resp.status_code, solr_message)) pysolr.SolrError: Solr responded with an error (HTTP 400): [Reason: undefined field status] Failed to query Solr using '((android) AND status:(approved))': Solr responded with an error (HTTP 400): [Reason: undefined field status] Traceback (most recent call last): File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/haystack/backends/solr_backend.py", line 138, in search raw_results = self.conn.search(query_string, … -
Django can't find my environment variable? VIEW_DB_USER not found. Declare it as envvar or define a default value
I am developing an app in django and I pushed it on Heroku. I want to query my database with SQL in my views.py, so I connect to my database with connect method. But when it comes to deploying my app, I want to hide my database credentials in environment file. However, I run into VIEW_DB_USER not found. Declare it as envvar or define a default value. (error at view_db_user = config("VIEW_DB_USER") ) Here is my views.py: import os import django_heroku from decouple import config import dj_database_url view_db_user = config("VIEW_DB_USER") view_db_password = config("view_db_password") view_db_host = config("view_db_host") view_db_database = config("view_db_database") mydb = pg2.connect(user=VIEW_DB_USER, password=view_db_password, host=view_db_host, database=view_db_database) Here is my .env file: SECRET_KEY = 'credential_1' VIEW_DB_USER = 'credential_2' view_db_password = 'credential_3' view_db_host = 'credential_4' view_db_database = 'credential_5' So from what I see I think the problem is that the function config here somehow is not working properly. But why? Please note that this does not work both in local and on heroku. Also note that SECRET_KEY contains a password of another database that perfectly works, being this passwork stored in my .env file. -
Django - render object image from the model itself or use a different model
I'm a bit in doubt regarding on how and what's the best approach for displaying images through Django. Of course, not serving the images from the database. So, for instance, let's take the User model that comes out of the box with Django. It is not recommended to alter the model, but use a different model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='user-profile-pics') Ok. So, this works fine. Now, let's say I have a different model for which I want to store images as well (e.g.: products). This means that for each product I have to store an image. Is it recommended to use a different model as above or since this is a custom model we can save the image within this model itself? Thanks -
Is it possible to submit multiple forms at once using Django views?
What I want to accomplish is to be able to submit multiple forms contained on one page. What I have currenlty done is supplied a view that returns 8 forms. Is it possible, within the template, to have lets say a button that will submit all of the forms contained on the page in one POST request? Here is some code from my view: def get_all_forms(request): context = {} if request.method == 'POST': return else: for x in range(8): context[x] = Form() return render(request, 'app/all_forms.html', {'form': context}) -
how to create in template in django application
I am following the tutorial on polls application,now am in part 3 but got confused on how to create a template so that Django’s template system separates the design from Python by creating a template that the view can use. The basic instruction is as follow: "First, create a directory called templates in your polls directory. Django will look for templates in there The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS. Within the templates directory you have just created, create another directory called polls, and within that create a file called index.html. In other words, your template should be at polls/templates/polls/index. html. Because of how the app_directories template loader works as described above, you can refer to this template within Django as polls/index.html." Now my question is how do I create this because I understand the whole of the tutorial? I need someone to come down to my level as a beginner. Thank you. -
Django recursive logging crashes Python 3 interpreter, swallowing logs
While load testing the Python 3 branch of our application, I noticed the following log entries, indicating that the maximum recursion depth had been reached, resulting in the interpreter being restarted. This leads to a massive performance hit and dropped requests. WARNING [reader.views] Initializing library objects. INFO [multiserver] Initializing ServerCoordinator with subscriptions: ['msync'] --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- --- Logging error --- Error: maximum recursion depth exceeded When looking into the issue, I noticed this other SO question which I believe describes our situation, and that question led to THIS bug report and THIS patch. My immediate goal is to make sure error and stacktrace information is properly logged, so that we can track down this issue. According to the Python 3 source there should be a lot more information coming after Logging Error, but that information is totally omitted. I've traced the core Python code responsible for those … -
How do I display large numbers with commas using Django views and display it in TEMPLATES
based on my research, they used javascript to display large numbers more nicely with commas How do I display large numbers with commas? HTML but in my case, i dont want to use javascript, i would like django views rather than javascript and post it in my html this is my views.py total_paid=SchoolFeesMasterList.objects.filter(Payment_Types__in=studentenroll.values_list('Payment_Type')).order_by( 'Display_Sequence').aggregate(Sum('Amount'))['Amount__sum'] or 0 if you notice in my views, I compute the total Amount of SchoolFeesMasterList so i get the result 35500 i just want to put commas in result just like this 35,500 html <tr> <td>{{total_paid}}</td> </tr> models.py class SchoolFeesMasterList(models.Model): Education_Levels= models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True) Payment_Types = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE,blank=True) School_Fees_Type= models.ForeignKey(SchoolFeesType, related_name='+', on_delete=models.CASCADE,blank=True) Amount = models.FloatField() -
Set Django's RequestFactory() method to equal 'POST'
Example view function: def example_view(request): if request.method == "POST": print(request.session['Key']) return HttpResponse("Success") Test case to test view: from django.contrib.sessions.backends.db import SessionStore from django.test import RequestFactory, TestCase from website.views import example_view class ExampleTestCase(TestCase): def test_example(self): # Create request and session request = RequestFactory() request.session = SessionStore() request.session['Key'] = "Value" response = example_view(request) self.assertEquals(response.status_code, 200) urls.py file in case anyone asks for it: urlpatterns = [ path('example', views.example_view, name="example_view"), ] Error Response: AttributeError: 'RequestFactory' object has no attribute 'method' Without: if request.method == 'POST': this works as expected. How do I set the request.method equal to post? -
Django-filter : how to use a function on an attribute inside a filtering method?
I'm building a filtering system with django-filters and I have a problem when using a custom filtering method. I have two models Plat and UserAdvanced which both have a location attribute corresponding to a Point from GeoDjango (it doesn't matter if you are not familiar with GeoDjango, the error is not GeoDjango related). models.py class UserAdvanced(models.Model): location = models.PointField(blank = True, null = True) class Plat(models.Model): location = models.PointField(blank = True, null = True) I want to filter all the Plat objects that are located at a distance less or equal than a value from the location of a UserAdvanced object. When I'm doing this in the shell, it works perfectly : location2 = useradvanced_object.location Plat.objects.filter(location__distance_lte=(location2, D(m=1000))) Note : distance is a build-in function of GeoDjango that can be applied to a point. The problem is that, when I'm doing exactly the same thing inside of a filtering method, I get an error. Here is the code : filters.py from actualites.models import Plat from django.contrib.gis.geos import Point from django.contrib.gis.geos import * from django.contrib.gis.measure import D import django_filters class PlatFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(PlatFilter, self).__init__(*args, **kwargs) distance_filter = django_filters.NumberFilter( field_name='location', method='distance_method' ) class Meta: model = Plat … -
Make (& test) 2 fields unique in Django Model
I have a model UserSite. Every User could have multiple sites. I now have to make them unique. So a site can't be added to a user if it already is appointed to that user. My Model code is: class UserSite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sites") site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name="users") class Meta: unique_together = ("user", "site") All fine. Now I want to make a test class who tests if this works. My test class: from rest_framework.test import APITestCase from models import UserSite from factories import SiteFactory from factories import UserFactory class TestUniqueUserSite(APITestCase): def setUp(self): self.user = UserFactory() self.test_site = SiteFactory() self.test_site_2 = SiteFactory() self.user_site = UserSite.objects.create(user=self.user, site=self.test_site) def test_user_site_is_unique(self): """ Check if a new UserSite is unique """ self.user_site1 = UserSite.objects.create(user=self.user, site=self.test_site) This test gives no errors, the UserSite can be created. What do I wrong? The testing or the unique field? or both hehe, thanks! -
Django TinyMCE TypeError
I installed django-tinymce==2.8.0 and tried using it in my Email model: class Email(models.Model): body = tinymce.models.HTMLField() Then declared a form (just using autocomplete_light if the parent class confuses you): class EmailForm(GenericModelForm): class Meta: fields = ['body'] body = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) The widget for the HTMLField should be automatically TinyMCE but I included it just in case. After instantiating the form EmailForm(), I am getting the following error when outputting it in a template {{ form }} or in the very view just for testing it out str(form): TypeError: build_attrs() takes at most 2 arguments (3 given) That's in the tinymce/widgets.py file. Anything I'm missing here? I wonder if using django-tinymce is even worth the hassle or I just just have a regular CharField and use the js plugin separately instead. Any benefit in using the Django package? -
What is the right way to fetch data that is being automatically posted to the URL that I'm developing the app on in Django?
There is data being automatically sent with POST request to the address I'm developing on, in format of JSON string. How should I properly fetch this data in my function based view, so I can manipulate with it? data = requests.get(url).json() did not work for me, it gives me back this error: django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLResolver list> (None:None) 'en/'>]], 'path': ''} At least, how can I test if there is any data being sent to the url? I'm developing in production env. -
Django monolithic application to microservice
I have Django rest framework project or I can say monolithic structured app. And the project structure and models define below. But now I want to break my monolithic application to microservice. So how can I organize my project structure and how can I make foreign key constraint in microservices ** There is the project folder structure ** \product \migrations __init__.py admin.py apps.py urls.py models.py tests.py \cart \migrations __init__.py admin.py apps.py urls.py models.py tests.py \order \migrations __init__.py admin.py apps.py urls.py models.py tests.py ** There is The Models ** class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() def __str__(self): return self.title class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) shipping_address = models.ForeignKey( 'Address', related_name='shipping_address', on_delete=models.SET_NULL, blank=True, null=True) billing_address = models.ForeignKey( 'Address', related_name='billing_address', on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey( 'Payment', on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey( 'Coupon', on_delete=models.SET_NULL, blank=True, null=True) being_delivered = models.BooleanField(default=False) received = models.BooleanField(default=False) refund_requested = models.BooleanField(default=False) refund_granted … -
What is difference between button and a href?
when I use below, <button class="px-2 py-1 rounded bg-red-500 text-white">{{cta}}</button> it works. but when I try url version, like: <a href="{% url 'moneylogs:create' pk %} " > <div class="px-2 py-1 rounded bg-red-500 text-white">{{cta}}</div> </a> error occure, i guess it is because pk is invalid. Reverse for 'create' with arguments '('',)' not found. 1 pattern(s) tried: ['moneylogs/create/(?P[0-9]+)/$'] i tried pk=moneylog.pk but it also doesn't work. my moneylog view is class moneylog_create(CreateView): form_class = forms.CreateMoneylogForm template_name = "moneylogs/create.html" def form_valid(self, form): moneylog = form.save() moneybook = moneybook_models.Moneybook.objects.get( pk=self.kwargs["pk"]) form.instance.moneybook = moneybook moneylog.save() form.save_m2m() return redirect(reverse("moneybooks:detail", kwargs={'pk': moneybook.pk})) and moneylog urls is like: app_name = "moneylogs" urlpatterns = [ path("create/<int:pk>/", views.moneylog_create.as_view(), name="create"), path("update/<int:pk>/", views.moneylog_update.as_view(), name="update"), path("<int:moneybook.pk>/delete/<int:moneylog.pk>", views.moneylog_delete, name="delete"), ] what is difference between button and a href? and why it doesn't work? how can i edit to a href version?