Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
KeyError at /category/news.html 'request' when trying to add category
So I am trying to add categories to articles, but I get a KeyError. This is my model: class Category(models.Model): title = models.CharField(max_length=100, db_index=True, null=True, blank=True) slug = models.SlugField(max_length=100, db_index=True) def __str__(self): return self.title @permalink def get_absolute_url(self): return ('view_blog_category', None, { 'slug': self.slug }) And this my view and urls: def view_category(request, slug): category = get_object_or_404(Category, slug=slug) return render_to_response('news/view_category.html', {'category': category,'posts': Article.objects.filter(category=category)[:5]}) urlpatterns = [ url(r'^news/(?P<slug>[^\.]+)', ArticleView.as_view() , name='view_blog_post'), url(r'^category/(?P<slug>[^\.]+).html', view_category, name='view_blog_category'), ] When I go to a category I added through django admin I get a KeyError at /category/news.html 'request' and it shows a error when rendering a inclusion tag. (A sidebar) If I remove this inclusion tag the KeyError goes away. But on all other pages the inclusion tag is working just fine. Only on this category page not. What is the problem? I think there is something wrong with my url but I can't seem to find the problem. -
Изучение Django [on hold]
Уже 8 месяцев изучаю python на курсах. Хочу самостоятельно изучить django2. Не подскажете хороший материал для изучения. Желательно на русском, но можно и на английском. -
In django how to pass RequestContext from the url declaration?
I've some url that I want to render a template without creating a view for each one, but inside I need a form with the csrf tag, so when the user post the form I get no csrf token becouse the template have no RequestContext render on it. How can I render templates declare in url and use csrf without creating a view for each one My urls.py path('path/', TemplateView.as_view(template_name='template.html')), The error: CSRF token missing or incorrect. UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. "A {% csrf_token %} was used in a template, but the context " -
Push dictionary to list via for loop
I want to push two dictionaries into a list via for loop. I don't get why it is not working. Could you pls help? :) result = {} results = [] for i in range(count): #->Count is 2, 2 different dictionaries result.update({ 'workitem_id' :str(api_results[i]['workitem_id']), 'workitem_header':api_results[i]['workitem_header'], 'workitem_desc':api_results[i]['workitem_desc'], 'workitem_duration':str(api_results[i] ['workitem_duration'])}) print(result) #-->Shows the two different dictionaries results.append(result) print(results) #-->Shows the list of two dictionaries, but the list contains the last dictionary for 2 times. Output print(result): {Dictionary 1} , {Dictionary 2} Output print(results): [{Dictionary 2} , {Dictionary 2}] The expected output of print(results): [{Dictionary 1}, {Dictionary 2}] -
How can I add one user to multiple groups?
Newbie here. I'm creating a project managemnet application where there is a group of teachers who have different(higher) permissions than students. the students are arranged in groups of 4 and each student group has a teacher assigned to them.So how do I add one user to 2 different groups? for creating groups I added the users individually to a new groups. Every teacher is added to the teacher group on registration itself So while adding a mentor I tried fetching a group by its name and adding using .user_set.add() models.py from django.db import models, transaction from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser, Group from phonenumber_field.modelfields import PhoneNumberField class Domain(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class MyUser(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) phonenumber = PhoneNumberField() class Teacher(models.Model): user = models.OneToOneField(MyUser, on_delete=models.CASCADE, primary_key=True) domain = models.ManyToManyField(Domain, related_name='interested_domains') def __str__(self): return self.user.username class Student(models.Model): user = models.OneToOneField(MyUser, on_delete=models.CASCADE, primary_key=True) division = models.CharField(max_length=4, blank=True) roll_no = models.IntegerField(blank=True) def __str__(self): return self.user.username class GroupData(models.Model): group = models.OneToOneField(Group,on_delete=models.CASCADE,primary_key=True) domain = models.ManyToManyField(Domain,related_name='primary_domain') def __str__(self): return self.group.name forms.py class GroupCreateForm(forms.ModelForm): user1 = forms.ModelChoiceField(queryset=MyUser.objects.filter(is_student=True), empty_label="(Choose a User)") user2 = forms.ModelChoiceField(queryset=MyUser.objects.filter(is_student=True), empty_label="(Choose a User)") user3 = forms.ModelChoiceField(queryset=MyUser.objects.filter(is_student=True), empty_label="(Choose a User)") user4 = forms.ModelChoiceField(queryset=MyUser.objects.filter(is_student=True), empty_label="(Choose a User)") … -
deleting image using modal id
I have a modal that shows the photos of the user and in that modal that has the photo has a trash icon for the user to delete the photo, and as soon as he clicks the trash, another modal appears asking if he is sure he wants to delete the photo. And confirming the photo is deleted. the problem is that you are always deleting the first photo, you are not deleting the photo that is in the modal. if I id in any photo in the middle of the gallery and click, this photo opens in the modal, the photo I chose, but when trying to delete, always delete the first photo of the gallery modalgallery.js $(function() { $('.pop').on('click', function() { $('.imagepreview').attr('src', $(this).attr('data-img-url')); $('#imagemodal').modal('show'); }); }); modalconfirmedelete.js $(function() { $('.pop2').on('click', function() { $('#delete').modal('show'); }); }); views.py def delete(request, id): photos = Photo.objects.get(id=id) photos.delete() return redirect('sistema_perfil') def perfil(request): photos_list = Photo.objects.filter(user=request.user.pk) usuario = Usuario.objects.all() form = UsuarioForm() data = {'usuario': usuario, 'form': form, 'photos': photos_list} return render(request, 'perfil.html', data) perfil.html {% for photo in photos %} <a class="pop" href="#" data-img-url="{{ photo.file.large.url}}"><img src="{{ photo.file.medium.url}}"class="img-thumbnail" width="200" height="200"> </a> <!-- Modal Gallery--> <div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog … -
Django ORM - model referencing another models ManyToMany field
I'm currently trying to setup some database models in djangos ORM. however im unable to figure out how i'm supposed to reference another models many-to-many- field. Project model class Project(models.Model): projectName = models.CharField(max_length=200) users = models.ManyToManyField(get_user_model()) projectOwner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='projectowner', default=1) The users = models.manytomanyfield(get_user_mode()) works fine and generates the correct relation in the database. now i want to add a new model that adds a many to many relation between rights and project_user so what the end result tables are supposed to look like: project: projectname - string projectowner - id of referenced user user: django orm auth user model rights: name description etc project_user: id project_id user_id rights_projectuser: id rights_id project_user_id now that last one (rights_projectuser) is what i dont know how to make. -
How DO I create category for product where I can implement category specific filters for product while not adding extra attribute to product
I am building Ecommerce app in Django . SO I hit a design roadblock where I can't Implement category specific filters for Product without adding unneccessary attributes to model for product . class Product(models.Model): image = models.ImageField(upload_to='product_images/') title = models.CharField(max_length=255) pub_date = models.DateTimeField(default=now()) subline = models.CharField(max_length=255) product_price = models.IntegerField() color = models.ForeignKey('Colors', on_delete=models.CASCADE, blank=True, null=True, to_field="name") size = models.CharField(max_length=255) details = models.TextField() category = models.ForeignKey('marketplace.MarketCategory', on_delete=models.CASCADE, blank=True, null=True) sub_category = models.ForeignKey('marketplace.MarketSubCategory', on_delete=models.CASCADE, blank=True) owner = models.ForeignKey(Vendor, on_delete=models.PROTECT) def __str__(self): return self.title -
Django Queryset for Getting Feeds from Following Users
I am trying to get feeds from following users such as Facebook, Instagram, and Twitter. I wrote a view to show feeds from following people. class Following(View): def get(self, request): user = request.user posts = models.Post.objects.filter(creator__in=user.following.all()).order_by('created_date')[:5] I was worrying if it might cause a performance issue due to user.following.all() part. I do not know why filter(creator=user.following) does not work. following is a self-referencing ManyToManyField. followers = models.ManyToManyField("self", blank=True) following = models.ManyToManyField("self", blank=True) Is there any better solution? I have another issues with counting a number of ManyToManyFields. class Popular(View): def get(self, request): user = request.user posts = models.Post.objects.annotate(number_of_likes=Count('likes'), number_of_comments=Count('comments')).filter(Q(channels__users=user) & (Q(number_of_likes__gte=5) | Q(number_of_comments__gte=5))).order_by('created_date')[:5] It is so long because likes__count and comments__count did not work. The only case I found on the internet that works was this, using annotate(). Is there a better solution for this? I want to filter out posts that have channels a user is subscribing and among them, I want to only show number of likes or number of comments are above certain range. Why does this not work? models.Post.objects.filter(Q(channels__users=user) & (Q(likes__count__gte=5) | Q(comments__count__gte=5))).order_by('created_date')[:5] class Comment(news_models.TimeStampedModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') class Like(news_models.TimeStampedModel): comment = models.ForeignKey(Comment, null=True, on_delete=models.CASCADE, related_name='likes') class Channel(models.Model): name = models.CharField(max_length=100, blank=False, unique=True) users … -
Skip a level with {{ block.super }}
Base template defines a block with some content: base.html: <!doctype HTML> <html><head> <!-- blah blah --> {% block very_kewl %} <marquee><b><i><u>this is very kewl</marquee></b></i></u> <!-- disclaimer: this is not valid HTML! --> {% endblock very_kewl %} </html> Then a child template clears the block: actual_page.html: {% extends 'base.html' %} {# very many other stuff, part 1 #} {% block very_kewl %}{% endblock %} {# very many other stuff, part 2 #} What I want to achieve is to keep the "very kewl" content on the page. An approach that works is to simply copy the entire actual_page.html into the project template dir and omit the line {% block very_kewl %}{% endblock %}. This works, but the downside is that I also have to repeat all the other parts of the template, some of which are likely to change in the future. So the question is how can I show that "very kewl" content from the base template without also repeating all the other stuff in the actual_page.html? Ideally, I would be able to do something like this, but of course, this doesn't work: project_templates/actual_page.html: {% extends 'actual_page.html' %} {% block very_kewl %}{{ block.super.super }}{% endblock %} -
How to arrange search results by the date they were created on?
I made a search bar but it gives the queries in an old to new order i want to change that to a new to old. I want to see the recent matches for my search first then the more old ones. views.py search_term='' if 'search' in request.GET: search_term_extract = request.GET['search'] search_term = Blog.objects.filter(Q(title__icontains=search_term_extract)|Q(author__username__icontains=search_term_extract)) paginator = Paginator(search_term, 8) page = request.GET.get('page') paginator_page = paginator.get_page(page) results=search_term.all()['-date_posted'] message=True nav=False and models.py class Blog(models.Model): title=models.CharField(max_length=100) content=models.TextField(blank=True) date_posted=models.DateTimeField(default=timezone.now) author=models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title -
How to change URL on render in Django?
When I was searching about it in google, i found only answers that didn't help actually help me. My problem is really simple: I just want to change URL in browser, when I render. (When i was searching i found that i can't pass any data to redirect() function so it isn't the good way). "post" method triggers when user submit form (there will be some validation etc. but at the end of the day I'll need to render template (home if user wrote credentials correctly or login again to show user if he wrote credentials incorrectly)). When I render some template, URL in browser will be "/submit_login" instead of "/login". Here's this part of code: in urls.py path('login/', login.as_view(), name='login'), path('submit_login/', login.as_view(), name='submit_login'), in views.py class login(View): template_src = "login.html" # showing user login view def get(self, request): form = AuthenticationForm() return render(request, self.template_src, { 'form': form }) #This triggers when user submit form def post(self, request): #I tried request.path_info but it didn't work also #request.path_info = "/login/" form = AuthenticationForm(request.POST) #When I call this URL is still "/submit_login" instead of "/login" return render(request, self.template_src, {'form': form }) template (if someone wants to see what I am trying to … -
Running Django server from Visual Studio 2017
I recently tried to import my django project into Visual Studio 2017 using existing python project which worked. When I try to start the server however I get the error: 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? My PYTHONPATH variable includes the path to python and django: C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django C:\Users\Admin\AppData\Local\Programs\Python\Python36-32 (as well as lib and dlls) I don't know about the virutal environment part. Do I need to do a setting somewhere in Visual Studio? From the console in the same folder I can run the server with: path>python manage.py runserver which I thought is what visual Studio also does. -
Postgres nested arrayfield django
Suppose I have the following row: First Name Peter Last Name Jones Sizes 35 37 39 42 44 12 37 null null null 15 17 How to query sizes so that exactly one from each column occurs? Person.objects.get(sizes=[35, 37, 39, 42]) returns Person.objects.get(sizes=[42, 35, 37, 39]) returns Person.objects.get(sizes=[35, 37, 39]) doesn't return Person.objects.get(sizes=[44, 12, 39, 42]) returns Person.objects.get(sizes=[35, 44, 39, 42]) doesn't return So, I supply some list and each value from the list should occur in each column exactly once. I need two options order matters and order doesn't matter. Order matters: Person.objects.get(sizes=[42, 35, 37, 39]) doesn't return Order doesn't matter: Person.objects.get(sizes=[42, 35, 37, 39]) returns Thank you. -
How to run a view function containing an operation parameter without reloading page
I am creating a site which allows users to post comments and like posts. I have created a view function which allows a user to like posts but am not sure how to implement ajax or a similar technique to perform the request without reloading the page. So that the user doesn't lose where they were on the page and have to scroll down to find it after liking a post. In my views.py: #this is the function i wish to run without reloading def like(request, operation, id): like = Post.objects.get(id=id) if operation == 'add': Like.make_like(request.user, like) elif operation == 'remove': Like.lose_like(request.user, like) return HttpResponseRedirect('/Feed/') #this is the view in which it is called class FeedView(TemplateView): template_name = 'feed.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) try: like = Like.objects.get(user=request.user) likes = like.posts.all() except Like.DoesNotExist: like = None likes = None args = { 'form': form, 'posts': posts, 'users': users, 'likes': likes } return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = HomeForm() return HttpResponseRedirect('/Feed/') args = {'form': form, 'text': text} return render(request, self.template_name, args) feed.html: {% for post in … -
How to upload image as url, not file?
I want to upload images not from files but from url's that are submitted by the user, via a put call with a payload like {"image_url":"http://example.com/1.jpg"}. What is the recommended way of doing this with DRF? (So far my only option is to reimplement everything manually within my model view set. Is ther any better solution?) -
Dropdown option from template to views
I am making a project in Django and I want to print out information on the basis of the Dropdown option a user selects from the dropdown list. I am not able to get the output however there are no errors. This is my template: <form method="post"> {% csrf_token %} <select name="drop1" class="form-control"> <option>Happy</option> <option>Sad</option> </select> </form> and This is my views.py: if request.method == "POST": mood = request.POST['drop1'] print(mood) I just want the value of the dropdown to be printed out so I can use it later on. -
how to download json response as file?
How to download json file django view def downloadfiles(request, user_id): try: filename = str(user_id)+'.json' file_path = os.path.join(os.environ.get('HOME'), filename) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/json") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response except: return Http404 I tried this instead of downloading it is just displaying json content in the file -
How do I get nginx to escape % signs in page address
I am running a website using django with nginx as my database. In my development environment any addresses that contain a "%" sign automatically get escaped as %25 and work fine (running sqlite3 in development) but in production the % sign is not escaped and causes a "400 bad request" the address format is domain.com/{pk}/{title that contains %} django is then using the pk to get the item from the database. -
django can't find new sqlite version? (SQLite 3.8.3 or later is required (found 3.7.17))
I've cloned a django project to a Centos 7 vps and I'm trying to run it now, but I get this error when trying to migrate: $ python manage.py migrate django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). When I checked the version for sqlite, it was 3.7.17, so I downloaded the newest version from sqlite website and replaced it with the old one, and now when I version it, it gives: $ sqlite3 --version 3.27.2 2019-02-25 16:06:06 bd49a8271d650fa89e446b42e513b595a717b9212c91dd384aab871fc1d0f6d7 Still when I try to migrate the project, I get the exact same message as before which means the newer version is not found. I'm new to linux and would appreciate any help. -
how to fix read only permission on media-server heroku djangorest?
I have a web api deployed in heroku built with django rest , and I have to handle some pictures and files, and for that I added a media-server directory in the app, when I run it locally there are no problems, but when deployed in heroku I have a read-only error. I tried to chmod 777 the dir with heroku bash and in my dir locally before pushing it urls.py ... urlpatterns = [ ... # url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT,}) ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) setting.py ... STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = "/static/" MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),'static-server','media-root') my dir: static-server |_media-root |_document |_logo |_modele |_version the error: Exception Type: OSError at /marque/new Exception Value: [Errno 30] Read-only file system: '/static-server' if anyone can help me find a solution so I can upload files and pictures to my heroku app -
I wonder what is this exactly funtionally act {% for post in post_list %}
I'm making Django Web Project for school project. and I almost finished to watch one of django lecture in udemy but i don't understand yet one of code in project -> {% for post in post_list %} {% extends "posts/post_base.html" %} {% block post_content %} <body> <div class="card-columns"> {% for post in post_list %} <div class="card shadow-sm p-3 mb-5 bg-white rounded"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/UA_Flight_175_hits_WTC_south_tower_9-11_edit.jpeg/1024px-UA_Flight_175_hits_WTC_south_tower_9-11_edit.jpeg" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"><a href="{% url 'posts:single' username=post.user.username pk=post.pk %}">{{post.title}}</a></h5> <p class="card-text ">{{post.text|safe}}</p> <cite title="Source Title"><a href="{% url 'posts:for_user' username=post.user.username %}"><small>by {{post.user.username}}</small></a></cite> <button type="button" class="btn btn-info btn-sm">원문 국가 표시</button> </div> </div> {% endfor %} </div> </body> {% endblock %} #urls.py path('', views.PostList.as_view(), name="all"), path("new/", views.CreatePost.as_view(), name="create"), path("delete/<int:pk>/", views.DeletePost.as_view(), name="delete"), path("by/<username>/",views.UserPosts.as_view(),name="for_user"), path("by/<username>/<int:pk>/",views.PostDetail.as_view(),name="single"), #views.py class PostList(generic.ListView): model = models.Post class MainPostList(generic.ListView): model = models.Post template_name ="posts/main_post_list.html" class CreatePost(LoginRequiredMixin, generic.CreateView): fields = ('title', 'text') model = models.Post def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeletePost(LoginRequiredMixin, generic.DeleteView): model = models.Post success_url = reverse_lazy("posts:all") def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) def delete(self, *args, **kwargs): messages.success(self.request, "Post Deleted") return super().delete(*args, **kwargs) class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" class PostDetail(generic.DetailView): model = models.Post def get_queryset(self): queryset = super().get_queryset() return queryset.filter( user__username__iexact=self.kwargs.get("username") I wonder … -
Django Admin: list_filter and date_hierarchy with def function's variable
This is my models.py and admin.py file where I was supposed to do a filter with 'reportbranch' and date_hierarchy with 'reportdate'. but it is throwing following errors: ERRORS: <class 'reports.admin.ReportSummaryAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'reportbranch', which does not refer to a Field. <class 'reports.admin.ReportSummaryAdmin'>: (admin.E127) The value of 'date_hierarchy' refers to 'reportdate', which does not refer to a Field. models.py class DailyReport(models.Model): report_type = models.CharField(max_length=500, choices=REPORT_TYPE, verbose_name="Type") date = models.DateField(verbose_name="Date") branch = models.ForeignKey(Branch, on_delete=models.CASCADE, verbose_name="Branch") added_by = models.ForeignKey(User, editable=False, on_delete=models.CASCADE, null=True, blank=True) added_at = models.DateTimeField(auto_now=True, editable=False) def __str__(self): return str(self.date) + ' - ' +self.branch.name class ReportItem(models.Model): particular = models.ForeignKey(Particular, on_delete=models.CASCADE, verbose_name="Particular") Report = models.ForeignKey(DailyReport, on_delete=models.CASCADE) total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="Total Amount") quantity = models.IntegerField(verbose_name="Quantity") remarks = models.CharField(max_length=5000, verbose_name="Remarks", null=True, blank=True) class ReportSummary(ReportItem): class Meta: proxy = True verbose_name = "Daily Report Summary" verbose_name_plural = "Daily Report Summaries" def reportdate(self): return self.Report.date def reportbranch(self): return self.Report.branch.name admin.py class ReportSummaryAdmin(admin.ModelAdmin): list_display = ['reportbranch','reportdate','particular','Report','total_amount','quantity'] list_filter = ['particular','reportbranch'] date_hierarchy = 'reportdate' Why it is throwing such issue, do I need to define anything with init function? I am confused over this issue's cause and its fix. -
css file is not loaded in django how to solve it
I tried django Sample project just add css style in html but its not working .many times i facing this issue inside css is working fine but static style.css is not working.I tried to check what is the mistake but I dono how to solve it.can please check my code how to solve it this issue index.html {% load staticfiles %} <html> <head> <link rel="stylesheet" href="{% static 'style.css' %}" type="text/css"/> </head> <body> <h1>Hello</h1> </body> </html> style.css h1 { color:rebeccapurple; } settings.py Django settings for loginpage project. Generated by 'django-admin startproject' using Django 2.1.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'bp@96qw+o0cky+#+@h1+z5)#6&08l$i@^+rbhcwycs$rb5xnyq' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'loginpage.urls' TEMPLATES = … -
After adding <a href="{% url 'jmiforums:answer' subforum.subform_name ques.id %}">Answer</a>, error NoReverseMatch at /cpp/1/view/
error: NoReverseMatch at /cpp/1/view/ Reverse for 'answer' with arguments '('', 1)' not found. 1 pattern(s) tried: ['(?P<subforum_name>[-a-zA-Z0-9_]+)\\/(?P<ques_id>[0-9]+)\\/answer\\/$'] urls.py: path("<slug:subforum_name>/<int:ques_id>/view/", views.view_question, name="view_question"), path("<slug:subforum_name>/<int:ques_id>/answer/", views.answer, name='answer'), views.py: def view_question(request, subforum_name, ques_id): ques = Question.objects.get(pk=ques_id) subforum = Subforum.objects.get(subforum_name=subforum_name) ans = Answer.objects.filter(ques_id=ques_id).values() com = Comment.objects.filter(ques_id=ques_id).values() form2 = Comments(request.POST or None) if form2.is_valid(): comment = form.save(commit=False) comment.user_id = User.objects.get(pk=request.user.pk) comment.ques_id = Question.objects.get(pk=ques_id) comment.save() return HttpResponseRedirect("/{subforum_name}/{ques_id}/view".format(subforum_name=subforum_name, ques_id=ques_id)) context = { 'ques': ques, 'subforum': subforum, 'ans': ans, 'com': com, 'form2': form2, } return render(request, 'jmiforums/view_question.html', context) view_question.html: <a href="{% url 'jmiforums:answer' subforum.subform_name ques.id %}">Answer</a> I think problem is in view_question.html link but don't know what. Thanks in advance.