Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Jquery - after cloning div each function works only on original div not cloned div - not looping cloned div
I spent three days questioning why it is not looping my cloned Div for calculating debit and credit of my account transactions. The debit and credit total needs to added up whenever I change the input value of these fields. But when I change first row it is updating correctly. But not on subsequent rows, still showing the first record fiqure only in summary bottom debit/credit total: (That is my updatetotal() taking on first div input fields only for calculation). this is my html: {% extends 'wstore_base_generic.html' %} {% block content %} <form action="" method="post" class="w-auto" id="new_trans_form" xmlns:width="http://www.w3.org/1999/xhtml"> <div class="row mt-1 mb-4" > <div class="col-md-12"> <div> <div class="headerctr"> <h3>JV</h3> <!-- <div> --> <!-- <h3 > --> <!-- </h3> --> </div> <div class="card-body" > {% csrf_token %} <div 38rem class="row style= width:18"> <div class="col"> <label>Transaction Date</label> <input type="date" class="form-control" name="{{form.fh_dt.name}}" value=" {{current_date}}" readonly> {% if form.fh_dt.errors %} {% for error in form.fh_dt.errors %} <small class="text-danger">{{error}}</small> {% endfor %} {% endif %} </div> <div class="col-sm" > <label>Transaction Number</label> <input type="number" class="form-control" name="{{form.fh_no.name}}" value="{{transaction_number}}" readonly> {% if form.fh_no.errors %} {% for error in form.fh_no.errors %} <small class="text-danger">{{error}}</small> {% endfor %} {% endif %} </div> <div class="col"> <input type="hidden" class="form-control" name="{{form.fh_type.name}}" required readonly value="JV"> … -
Django unique together constraint in two directions
So I have some models that look like this class Person(BaseModel): name = models.CharField(max_length=50) # other fields declared here... friends = models.ManyToManyField( to="self", through="Friendship", related_name="friends_to", symmetrical=True ) class Friendship(BaseModel): friend_from = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="friendships_from") friend_to = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="friendships_to") state = models.CharField( max_length=20, choices=FriendshipState.choices, default=FriendshipState.pending) So basically, I'm trying to model a Facebook-like friends situation, where there are different persons and one can ask any other person to be friends. That relationship is expressed through this last model Friendship. So far so good. But there are three situations I'd like to avoid: A Friendship can't have the same person in the friend_from and friend_to fields Only one Friendship for a set of two Friends should be allowed. The closest I've got to that, is adding this under the Friendship model: class Meta: constraints = [ constraints.UniqueConstraint( fields=['friend_from', 'friend_to'], name="unique_friendship_reverse" ), models.CheckConstraint( name="prevent_self_follow", check=~models.Q(friend_from=models.F("friend_to")), ) ] This totally solves situation 1, avoiding someone to befriend with himself, using the CheckConstraint. And partially solves situation number 2, because it avoids having two Friendships like this: p1 = Person.objects.create(name="Foo") p2 = Person.objects.create(name="Bar") Friendship.objects.create(friend_from=p1, friend_to=p2) # This one gets created OK Friendship.objects.create(friend_from=p1, friend_to=p2) # This one fails and raises an IntegrityError, which … -
Can't Activate Virtualenv on Powershell
I'm trying to learn Django. To start, I needed to install Python, Django, and Virtualenv. These are all installed with no errors. But now that I want to start a project and run virtualenv, I can't activate it in the powershell. I used this command to make a virtualenv: python -m virtualenv venv Now the tutorial says that I have to activate virtualenv like this: . \scripts\activate but it gives me this error: . : The term '\scripts\activate' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:3 + . \scripts\activate + ~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (\scripts\activate:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException What should I do? -
Filed to load resource: the server responded with a status of 404 (Not Found)
My images are not loading in a template. I was placing them in admin, so everything should be ok but,no. Model field class Guide(models.Model): image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = "/static/" MEDIA_URL = '/trips/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'trips/media/') Project tree Template {% if item.image%} <img src="{{item.image.url}}" alt="" style="max-height:300px"> {%else%} <img src="{%static 'avatar_sample.png' %}" id="uploaded_image" class="img-responsive img-circle" /> {%endif%} -
I am working on a React Django project I want to integrate opencv webcam django into react webcam so that the feed from the react js goes to opencv
This topic has some limited resources I am working on this React Django Project a real time face detection project I am using react in frontend with django backend and I have connected django with react my django opencv live webcam is working fine but how to connect opencv webcam with react webcam or any way to show the opencv webcam live on react js front page please help if anyone has some resources or links. -
Django Model conditional Validations
i have made an api on which a customer is sending his/her details for payment by making post request, so need to validate this data on model level,How can i validate a model field by comparing it to the other model fields For example: models.py Orders(models.Model): amount = models.DecimalField(max_digits=19, decimal_places=4) currency = models.CharField(max_length=3,choices=[('INR','INR')]) more choices are to be added payee_pan = models.CharField(max_length=10) Validation required : payee_pan must be present if currency is 'INR' and amount is greater than 50000. in order to validate it i am using model.full_clean() while saving the the model object in views.py views.py try: orders.full_clean() except ValidationError: return Response({"Error message":"invalid request body"}) else: orders.save() i would really appreciate if someone helps me in this as m stuck at this point for so long.enter code here -
Authenticate the django user using phone email and username
I am trying to achieve a login functionality like so that users can log into using their Email or Phone number or it's username as well but Django provides only email field in it's User model so that I've created an another model with One-To-One-Relation to User model and provided the phone number column but now I don't know how to achieve such functionality which I mentioned earlier. my models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.IntegerField(choices=USER_TYPE, default=3) mobile = models.BigIntegerField(unique=True) my views.py (I know it's a mess but I can't figure out how to have such functionality) def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) messages.success(request, 'You are logged in successfully!') return redirect('/dashboard') else: user = auth.authenticate(profile_phone=username, password=password) if user is not None: auth.login(request, user) messages.success(request, 'You are logged in successfully!') return redirect('/dashboard') else: user = auth.authenticate(email=username, password=password) if user is not None: auth.login(request, user) messages.success(request, 'You are logged in successfully!') return redirect('/dashboard') else: messages.error(request, 'Invalid username or password') return redirect('/login') else: if request.user.is_authenticated: messages.success(request, 'You are already logged in') return redirect("/dashboard") return render(request, … -
How can I send a reset password email on Django?
During the process of creating my first website using Django framework, I encountered a little problem that I couldn't found a solution yet. So, when an user wants to reset his or her password, i'd like to send to him/her a reset mail. So far, I have this: urls.py from django.contrib.auth import views as auth_views ...... path('password-reset/', auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html'), name='password_reset'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html')), .... settings.py EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_POST = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('traces_email') EMAIL_HOST_PASSWORD = os.environ.get('traces_email_password') I created a token generator for my link: token_generator.py from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() When I go through the reset flow, it does not send any email. It is still sent to my terminal. Can somebody help me with this issue? Thank you so much for your time! -
can we insert data into django default database sqlite3 without using models?
like without importing models and using the following commands: conn=sqlite3.connect("db.sqlite3") c=conn.cursor() c.execute("sql command") I am new to Django ,could you please??? -
'NoneType' object is not iterable' when using chrome browser
I get this error: 'TypeError at /' with the exception value: ''NoneType' object is not iterable' when i run my Django project on my local host. This only occurs when i'm specifically using the chrome browser ONLY. When i run my local host on safari, there are no issues. I am pretty certain that my code is not at fault, because i was running it, and closed my laptop, and when i opened up my laptop again, it gave me this error, and i had not changed a single line of code. Also i'm sure that its not my code because it is working on safari as i have stated earlier -
Django URL with blank parameter
I am new to Django. I created a Django web app wherein after a user logs in, it will redirect to the basic_list template which contains a list of wines. In the basic_list template, there is a “manage account” button which will redirect to the manage_account template. However, when I click the manage account button, it loads to localhost:8000/manage_account// instead of having a parameter such as localhost:8000/manage_account/1/ if 1 is the pk value of the user who just logged in. What should I do? Any suggestions would be greatly appreciated. models.py from django.db import models class Wine(models.Model): name = models.CharField(max_length=300) year = models.IntegerField() objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.name class Account(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=20) objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.username urls.py from django.urls import path from . import views urlpatterns = [ path('', views.view_login, name='view_login'), path('login', views.view_login, name='view_login'), path('basic_list', views.view_basic_list, name='view_basic_list'), path('manage_account/<int:pk>/', views.manage_account, name='manage_account'), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import * from django.core.exceptions import ObjectDoesNotExist def view_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') account = Account.objects.get(username=username) if password == account.password: return redirect('view_basic_list') else: return render(request, 'myapp/login.html', … -
How to use add-to-cart functionality in Django and after adding item in table the button should be hidden/disable?
I'm using Django as a backend and PostgresSQL as a DB and HTML, CSS, JS as frontend. Well, I have successfully added data to Django and also in PostregsSQL with models. And the data are fetch to the item_list successfully. So, while doing this I have stuck in a major problem that is ADD-TO-CART, While I'm trying to do as same as this Website. Where a user: Click on add/choose button(mainpage.html) -> PRODUCT ITEM LIST DISPLAYED (itemlist.html) -> Selected PRODUCT (itemlist.html) -> Added Product succesfully (mainpage.html) AND add/choose button should be disabled and instead of the add/choose button EDIT & DELETE Button should appear. How the code will work. I have no IDEA (TOTALLY NOOB). Please do suggest. And I'm adding my code down below. The Code Goes Here.... models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) joined_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class Product(models.Model): brand = models.CharField(max_length = 100) title = models.CharField(max_length=200) view_count = models.PositiveIntegerField(default=0) def __str__(self): return self.title class Cart(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) product = models.ManyToManyField(Product, null=True, blank=True) rate = models.PositiveIntegerField() total = models.PositiveIntegerField(default=0) subtotal = models.PositiveIntegerField() def __str__(self): return "Cart:" + str(self.id) admin.py admin.site.register(Cart) class CartAdmin(admin.ModelAdmin): class Meta: Model = Cart … -
502 nginx bad gateway error when uploading video to digital ocean droplet
I get this error in my django app when I try uploading large files in my digital ocean droplet.but when I try uploading low file it works. -
Django some columns in a model is migrated
I have the following model from django.db import models class Todo(models.Model): content = models.CharField(max_length=100) created_at_one: models.DateField(auto_now_add=True) finished_at: models.DateField(null=True) is_completed: models.BooleanField(default=False) list = models.ForeignKey( "TodoList", related_name="todos", on_delete=models.CASCADE) class TodoList(models.Model): title: models.CharField(max_length=20) created_at: models.DateField(auto_now_add=True) Then when I run python manage.py makemigrations and python3 manage.py migrate, there is no error. But when I check the tables created, some columns are missing. I run .schema app_todo to check the tables of Todo CREATE TABLE IF NOT EXISTS "app_todo" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "content" varchar(100) NOT NULL, "list_id" bigint NOT NULL REFERENCES "app_todolist" ("id") DEFERRABLE INITIALLY DEFERRED); CREATE INDEX "app_todo_list_id_c59d99ef" ON "app_todo" ("list_id"); Only id, content and list_id are created and three columns missing. For TodoList: CREATE TABLE IF NOT EXISTS "app_todolist" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT); title and create_at are missing. Please let me know if there is additional information that I should provide. Thanks a lot! -
raise KeyError(key) from None KeyError: 'AWS_ACCESS_KEY_ID'
when i am trying to execute the command python manage.py runserver i got this error File "C:\Users\Thripura sai\PycharmProjects\pythonProjectbiddd\Online_Auction_System_Project\online_auction_system\settings.py", line 164, in <module> AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] File "C:\Users\Thripura sai\AppData\Local\Programs\Python\Python39\lib\os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'AWS_ACCESS_KEY_ID' i don't know what's wrong with my code this is the code in my os.py which i got error def __getitem__(self, key): try: value = self._data[self.encodekey(key)] except KeyError: # raise KeyError with the original key value raise KeyError(key) from None return self.decodevalue(value) please provide me a solution -
OAuth 2.0 redirect url with django
I am making 2 django apps (one is the client and the other is the provider) and i am having problem redirecting to the correct url (the one that i entered when client registerd to provider). Does anyone knows how and where the client app process and create the redirect url??? I build the provider using OAuth toolkit and the client with social-oauth -
How to solve SMTNotSupported extension by the server Error?
Actually i am creating a registration form using django and when user will submit it he will get successful registration mail but it will give me error SMTPNotSupported extension server. my settings.py file EMAIL_HOST = 'smpt.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = myusername EMAIL_HOST_PASSWORD = my password EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend I am sharing my error photo with you all. -
Django song not being added to 'favourite songs'
I want my users to be able to add certain songs to Favourite Songs but although the success message 'Added to favourite songs' but when I visit the Favourite Songs page, I see no songs there. How can I fix this? Thanks in advance! My models.py: class Songs(models.Model): title = models.CharField(max_length = 100) lyrics = models.TextField() author = models.CharField(max_length = 100) track_image = models.CharField(max_length=2083) def __str__(self): return self.title def get_absolute_url(self): return reverse('/', kwargs={'pk': self.pk}) My views.py: def home(request): context = { 'songs': Songs.objects.all() } return render(request, 'home.html', context) @login_required def add_to_fav_songs(request, **kwargs): fav_song = Songs.objects.filter(id=kwargs.get('id')) messages.success(request, f'Added to favourite songs') return redirect('/') class Fav_songs(ListView): model = Songs template_name = 'fav_songs.html' context_object_name = 'fav_song' paginate_by = 2 def get_queryset(self): return Songs.objects.filter(pk=self.kwargs.get('pk')) My favoutie_songs.html: {% for song in fav_song %} <article class="media content-section"> <div class="media-body"> <h2><a class="article-title" href="{% url 'song-detail' song.id %}">{{ song.title }}</a></h2> <div class="article-metadata"> <a class="mr-2" href="{% url 'author-songs' song.author %}">{{ song.author }}</a> </div> <br> <img class="card-img-bottom" height="339px" width="20px" src="{{ song.track_image }}"> </div> </article> {% endfor %} -
Django ListView Filter
In my project am using Django ListView and it works fine. What I want now is to list data from database but with filter. One of the field I want to filter is resolution_date. below is my code: class RequestListView(ListView): model = Customer_Requests template_name = 'requests_list.html' paginate_by=2 def get_queryset(self): filter_val=self.request.GET.get("filter","") order_by=self.request.GET.get("orderby","id") if filter_val!="": reqo=Customer_Requests.objects.filter(Q(request_name__icontains=filter_val) | Q(subject__icontains=filter_val)).order_by(order_by) else: reqo=Customer_Requests.objects.all().order_by(order_by) return reqo def get_context_data(self,**kwargs): context=super(RequestListView,self).get_context_data(**kwargs) context["filter"]=self.request.GET.get("filter","") context["orderby"]=self.request.GET.get("orderby","id") context["all_table_fields"]=Customer_Requests._meta.get_fields() return context The above code list everything from the table but I want the records where resolution date is empty. How can I achieve this? Thank you -
Django for loop from one DB table
I'm working on a livescore app and can't get matches within leagues in the table, nested for loop is empty. I only get listed leagues and I would like to have inside the leagues all the matches that belong to those leagues -Leaugue match match -League match match My DB Model: class basic_scores(models.Model): time_status = models.CharField(max_length=5) time_minute = models.CharField(max_length=5) localteam_data_name = models.CharField(max_length=255) visitorteam_data_name = models.CharField(max_length=255) scores_localteam_score = models.CharField(max_length=15) scores_visitorteam_score = models.CharField(max_length=15) country_name = models.CharField(null=True, max_length=255) league_name = models.CharField(null=True, max_length=255 View: def league(request): #live_list = football_nows.objects.all() live_list = basic_scores.objects.all() return render(request, 'league.html', {'live_list': live_list}) league.html: <h1>Live</h1> {% for league in live_list %} <center> <td>{{ league.league_name }}</td> {% for live in league %} <td>{{ live.time_minute }}</td> <td>{{ live.localteam_data_name }}</td> <td>{{ live.scores_localteam_score }} : {{ live.scores_visitorteam_score }}</td> <td>{{ live.visitorteam_data_name }}</td> {% endfor %} </center> {# This is a comment. #} {% endfor %} Browser result: -
Efficiently extract large amounts of data from Django ORM
I have a Django setup with PostgreSQL DB. One of the tables contains large amounts of data (>1e9 rows) and I need to efficiently iterate over a large subset of it. Currently, when I try to select a large amount of data it starts buffering the result and my computer runs out of memory. If I use .iterator() on QuerySet, it just hangs. If I try to use raw SQL and fetchall() it also starts buffering. I believe Django uses psycopg2 for PostgreSQL which has cursor.itersize parameter, but when I try to use it with cursor in Django it doesn't do anything. I know that the problem is not on database end, since I can execute the query using psql (with -A --variable="FETCH_COUNT=10000") and it starts loading immediately without using any memory. Extra info: The table has >10 columns, but I only need 2 of them, so if it is possible to only fetch selected for faster loading it would be nice. -
'QuerySet' object has no attribute 'name' Django
So I have a get function class HorseEquipmentView(APIView): lookup_url_kwarg = 'horse' def get (self, request, format = None): horse = 1 if horse != None: tab = [] #queryset = HorseEquipment.objects.raw('SELECT H.horse_id, E.name FROM horse_equipment H JOIN equipment E ON H.equipment_id = E.id WHERE H.horse_id =' + str(horse)) queryset = HorseEquipment.objects.filter(horse_id=horse).select_related("equipment") for i in queryset: i.equipment = Equipment.objects.filter(id = 1).name #equipment = HorseEquipment.objects.filter(horse_id=horse).select_related('equipment') serializer = HorseEquipmentSerializer(queryset, many = True) return Response(serializer.data) else: return Response(status = status.HTTP_400_BAD_REQUEST) and my Equipment Model: class Equipment(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(unique=True, max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'equipment' So it has id and name attributes but somehow it gives me error on my get function, precisely on my for loop where I refer to "name" attribute. Can you help me find out what's wrong? -
Django ManyToManyField prefetch multiple level
I created a mapping table for ManyToMany relationships. The model is roughly as below. //PageTemplate Model class PageTemplate(models.Model): id = models.AutoField(primary_key=True) page = models.ForeignKey( Page, null=False, related_name='pt_page' ) template = models.ForeignKey( Template, null=False, related_name='pt_template' ) created = models.DateTimeField(auto_now_add=True, verbose_name=_('Created At')) //Page Model class Page(models.Model): id = models.AutoField(primary_key=True) project = models.ForeignKey( Project, related_name='pages', on_delete=models.CASCADE, verbose_name=_('project_id') ) page_type = models.ForeignKey( ProjectType, related_name='pages', on_delete=models.CASCADE, verbose_name=_('page_type') ) page_template = models.ManyToManyField( 'Template', through='PageTemplate' ) ... //Template Model class Template(models.Model): id = models.AutoField(primary_key=True) @property def width(self): return self.page.page_type.width @property def height(self): return self.page.page_type.height ... After this, I created a serialize class. class PageTemplateSerializer(ExtendedValidationErrorSerializer): page_id = serializers.ReadOnlyField(source='page.id') page_type = serializers.ReadOnlyField(source='page.page_type') page_title = serializers.ReadOnlyField(source='page.title') page_order = serializers.ReadOnlyField(source='page.order') template_id = serializers.ReadOnlyField(source='template.id') template_width = serializers.ReadOnlyField(source='template.width') template_height = serializers.ReadOnlyField(source='template.height') class Meta: model = PageTemplate fields = ('page_id', 'page_type', 'page_title', 'page_order', 'template_id', 'template_width', 'template_height') This is not a problem, but Template has a reference to TamplateDetailItem, a class with detailed data inside Template. Reverse reference relation referencing TamplateDetailItem to Template. class TemplateDetailItem(models.Model): id = models.AutoField(primary_key=True) template = models.ForeignKey( Template, null=False, related_name='template_detail_items', ) ... That is, the structure is mapped to the PageTemplate as a many-to-many relationship (Page <-> Template), and the Template and TemplateDetailItem are mapped as a one-to-many relationships. (TemplateDetailItem -> … -
is it possible create export as CSV button when there is pagination in your HTML using plane javascript?
I am able to download the content on the current page but not able to download all the content coming to the table from the backend. // Quick and simple export target #table_id into a csv function download_as_csv(table_id, separator = ',') { // Select rows from table_id var rows = document.querySelectorAll('table#' + table_id + ' tr'); // Construct csv var csv = []; for (var i = 0; i < rows.length; i++) { var row = [], cols = rows[i].querySelectorAll('td, th'); for (var j = 0; j < cols.length; j++) { // Clean innertext to remove multiple spaces and jumpline (break csv) var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ') // Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv) data = data.replace(/"/g, '""'); // Push escaped string row.push('"' + data + '"'); } csv.push(row.join(separator)); } var csv_string = csv.join('\n'); // Download it var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv'; var link = document.createElement('a'); link.style.display = 'none'; link.setAttribute('target', '_blank'); link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string)); link.setAttribute('download', filename); document.body.appendChild(link); link.click(); document.body.removeChild(link); } I have hound similar question here with no answer. For the backend, I am using Django and to render a table using Vue.js.Any suggestions will be highly appreciated. TIA. -
Django error NoReverseMatch at / Reverse for 'add-to-fav-songs' with arguments '('',)' not found
So I want users to be able to add songs to a section called 'Favorite songs'(just like adding products to a cart in an e-commerce website) but I'm getting this error NoReverseMatch at / Reverse for 'add-to-fav-songs' with arguments '('',)' not found. 1 pattern(s) tried: ['add\\-to\\-fav\\-songs/(?P<pk>[0-9]+)/$']. Can anyone correct my code and show me how can I add songs to favorite songs. Thanks in advance! My models.py: class Songs(models.Model): title = models.CharField(max_length = 100) lyrics = models.TextField() author = models.CharField(max_length = 100) track_image = models.CharField(max_length=2083) def __str__(self): return self.title def get_absolute_url(self): return reverse('/', kwargs={'pk': self.pk}) My views.py: def home(request): context = { 'songs': Songs.objects.all() } return render(request, 'home.html', context) @login_required def add_to_fav_songs(request): fav_song = get_object_or_404(Songs) class Fav_songs(ListView): model = Songs template_name = 'fav_songs.html' context_object_name = 'fav_song' paginate_by = 2 def get_queryset(self): return Songs.objects.filter(id=self.kwargs.get('pk')) My urls.py: path('add-to-fav-songs/<int:pk>/', views.add_to_fav_songs, name='add-to-fav-songs'), path('favourite-songs/', Fav_songs.as_view(), name='favourite-songs'), My home.html: <form class="form" method="POST" action="{% url 'add-to-fav-songs' object.id %}"> {% csrf_token %} <div class="action"> <button class="like btn btn-danger" type="button"><span class="fa fa-heart"></span></button> </div> </form> My fav_songs.html: {% for fav_song in songs %} <article class="media content-section"> <div class="media-body"> <h2><a class="article-title" href="{% url 'song-detail' song.id %}">{{ fav_song.title }}</a></h2> <div class="article-metadata"> <a class="mr-2" href="{% url 'author-songs' song.author %}">{{ fav_song.author }}</a> </div> <br> …