Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove duplicates from the database table, alter the model with unique=True and makemigrations?
class CommonInfo(models.Model): name = models.CharField(max_length = 100) age = models.PositiveIntegerField() class Meta: abstract=True ordering=['name'] class Student(CommonInfo): home_group =models.CharField(max_length=5) class Meta(CommonInfo.Meta): db_table='student_info' Blockquote I have a similar database model with existing data. I want to add a uique=True on the field name. Is there any way I could remove the existing duplicate data before I alter the field name as unique? -
Exporting field data in many to many relationships using django-input-output only shows primary key
I am trying to export the data from my database from the django admin page using the django-import-export package. When I export a model, I also want to show the data in a particular field for every object in a many to many relationship. It looks something like this: models.py class Item(models.Model): part_number = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=250, blank=True) def __str__(self): return self.part_number class Bin(models.Model): name = models.CharField(max_length=50, unique=True) items = models.ManyToManyField(Item, blank=True) def __str__(self): return self.name admin.py class ItemResource(ModelResource): class Meta: model = Item fields = ('part_number', 'description') @admin.register(Item) class ItemAdmin(ImportExportModelAdmin): save_as = True resource_class = ItemResource class BinResource(ModelResource): class Meta: model = Bin fields = ('name', 'item__part_number') @admin.register(Item) class ItemAdmin(ImportExportModelAdmin): save_as = True resource_class = BinResource The way I would expect this to work is that if I export Items, I will get a document that has all the part numbers in one column and the description in another. This works just fine. However, I would also expect that when I export Bins, one column would show all the names, and another column would display a list of all the part numbers of the items that are associated with the bin. What I actually get is a … -
TypeError: __init__() got an unexpected keyword argument 'bot_id' when i pass a variable from views to form
I need to pass a variable from views to form to limit the selection of objects in the ModelChoiceField depending on the bot_id Tell me how to do it right, in the current implementation, the code gives an error TypeError: init() got an unexpected keyword argument 'bot_id'. My code: views.py def edit_question(request, bot_id, question_id): bot = get_object_or_404(SettingsBot, id=bot_id) question = get_object_or_404(Questions, id=question_id) QuestionInlineFormSet = inlineformset_factory(Questions, RelationQuestion, exclude=('bot',), fk_name='base', form=SubQuestionForm) if request.method == "POST": form = QuestionsForm(data=request.POST, instance=question) formset = QuestionInlineFormSet(request.POST, request.FILES, bot_id=bot_id, instance=question) if formset.is_valid(): formset.save() return redirect(question.get_absolute_url()) else: form = QuestionsForm(instance=question) formset = QuestionInlineFormSet(bot_id=bot_id, instance=question) return render(request, 'FAQ/edit_questions.html', {'question': question, 'bot': bot, 'form': form, 'formset': formset}) forms.py class SubQuestionForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.bot_id = kwargs.pop('bot_id', None) super(SubQuestionForm, self).__init__(*args, **kwargs) self.fields['sub'] = forms.ModelChoiceField(Questions.objects.filter(bot=self.bot_id)) class Meta: model = RelationQuestion fields = ['sub'] models.py class Questions(models.Model): question = models.CharField(max_length=30, verbose_name="Вопрос") answer = models.TextField(default="No text", verbose_name="Ответ на вопрос") id = models.BigAutoField(primary_key=True) bot = models.ForeignKey("SettingsBot", related_name="Бот", on_delete=models.CASCADE, verbose_name="Бот") general = models.BooleanField(default=False, verbose_name="Отображать на стартовой странице") created = models.DateTimeField(auto_now_add=True, verbose_name="Создан") updated = models.DateTimeField(auto_now=True, db_index=True, verbose_name="Изменен") class Meta: verbose_name = "Вопрос" verbose_name_plural = "Вопросы" ordering = ('-id',) def get_absolute_url(self): return reverse('FAQ:edit_questions', kwargs={'question_id': str(self.id), 'bot_id': str(self.bot)}) def __str__(self): return self.question def data(self): return [self.question, self.answer, self.id, … -
Automatically submit a value on click to a form using Javascript/Java in a Django form
I am working on a web app using Django/Python/Javascript/Java. The focal point is a map of the USA. A user should be able to click on a region and the value of that region should automatically query a database and return certain information. Currently, my code produces a const called regionName and the value of regionName is passed automatically as input to the search bar; however, from here a user needs to manually click the 'search' button to submit the form and query the database. As below: onRegionClick: function(event, code){ console.log('event', event, 'code', code); const regionName = map.getRegionName(code); console.log('regionName', regionName); $("#selection").val(regionName); }, }); What I am trying to do with the code is to automatically submit the value of regionName after it is passed to the search bar. Efforts thus far have been similar to the code below. $("#selection") - the form $("#q") - the name of the button $("#selection").on('change', function(){ if ($("#selection").val() === regionName ) { $("#q").click(); } }); This is not producing any errors, but it's not producing any results either. I've tried various substitutes along similar lines such as: .on('input'.. instead of 'change' .submit() instead of .click() I've also have an .autocomplete() method I'm using. I'm not … -
get() returned more than one Product -- it returned 2 Django Rest Framework
DRF returning this: get() returned more than one Product -- it returned 2!, when im trying to get objects from my DB by PK Serializers class ProductSerializer(serializers.ModelSerializer): # cat_id = serializers.SlugRelatedField(slug_field='cat_id', read_only=True) class Meta: model = Product fields = ('name', 'description', 'cat_id', 'use', 'diametr', 'len', 'color', 'photo') Views class CategoryProductView(APIView): def get(self, request, pk): product = Product.objects.get(cat_id=pk) serializer = ProductSerializer(product) return Response(serializer.data) Urls path('api/categorylist/<int:pk>', CategoryProductView.as_view()) -
Django serialize One to One
I have a model named client and it has a two foreign key relationships. One is to the region they are from and the other is to an agent. I am trying to serialize all clients. Using, use_natural_foreign_keys=True is giving me the region name. How would I get the agent name without using DRF? Model: class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Client(models.Model): name = models.CharField(max_length=20, default="") agent = models.ForeignKey("Agent", on_delete=models.CASCADE) region = models.ForeignKey("Region", on_delete=models.CASCADE) View: class ClientLog(View): page_limit = 100 def get_paginated_context(self, queryset, page, limit): if not page: page = 1 if limit: self.page_limit = limit paginator = Paginator(queryset, self.page_limit) page_obj = paginator.get_page(page) serialized_page = serialize("json", page_obj.object_list, use_natural_foreign_keys=True) serialized_page = [{**obj["fields"], **{"pk": obj["pk"]}} for obj in json.loads(serialized_page)] return { "data": serialized_page, "pagination": { "page": page, "limit": limit, "has_next": page_obj.has_next(), "has_prev": page_obj.has_previous(), "total": queryset.count() } } def get(self, request, *args, **kwargs): page = request.GET.get('page') limit = request.GET.get('limit') queryset = Client.objects.all() to_return = self.get_paginated_context(queryset, page, limit) return JsonResponse(to_return, status = 200) -
ModuleNotFoundError: No module named 'blog.models'
I was experimenting with my database and made some errors and messed up the whole database. I deleted the database and created a new blank db. When I go to makemigrations i get the error ModuleNotFoundError: No module named 'blog.models' refering to the line in my views.py where i import my models. I tried creating a a new project and moving the files over same error. Everything was working fine before I messed up the DB. Sorry for not a ton of information I dont know what the issue really is -
Django permissions view access for only one permission in the list
I have a Django class based view in which I am using the PermissionRequiredMixin. I would like a user who has at least one of the permissions in the permissions_required attribute to be able to access the view. From the Django documentation: The decorator may also take an iterable of permissions, in which case the user must have all of the permissions in order to access the view. So, if User1 has permission, "add_polls" and User2 has "change_polls", and I have a form view that lets a user add a poll and another view that lets a user change a poll (with permissions_required="add_polls" and permissions_required="change_polls" on each of those views, respectively), it works great. But, what if I have an interim page/view that has links to both of those views with permissions_required = ("add_polls", "change_polls") that I need the user to pass through first? Now, neither user will be able to access to that page because the users only have access to one or the other permission, not both - if I understand the documentation correctly, a user will need BOTH those permissions to access the interim page. If I did give both users access to both those permissions so … -
This QueryDict instance is immutable (Trying to manually set form data)
When I go to save. It will not allow me. I am trying to add details into the database through inputting the form manually. I am struggling to actually input the data into the form so I can save it. For example, I have tried to get the form data then set the data I would like it to be set to however Im guessing this is incorrect? I cannot find a command to set the form data manually. Is this possible? views from telnetlib import LOGOUT from django.shortcuts import redirect, render from django.http import HttpResponse from matplotlib import use from matplotlib.pyplot import get from matplotlib.style import context from werkzeug import Request from .models import Account, Question, sni, Option from django.contrib.auth.hashers import make_password, check_password from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, logout from django.contrib.auth import login as dj_login from django.forms import ModelForm, forms from django.contrib.auth.decorators import login_required from .forms import AccountAuthenticationForm, SNIForm, createUserForm, resultForm def login(request): context = {} if request.method == 'POST': username = request.POST.get('username').lower() password = request.POST.get('password') user = authenticate(request, userID = username, password = password) form = AccountAuthenticationForm(request.GET) if user is not None: dj_login(request, user) return redirect('dashboardPage') else: messages.info(request, "userID or password … -
How to know the key of a DRF Serializer DictField from within that field's child?
Let's say we have some Django Rest Framework Serializer (we'll call it "serializer") that has a custom DictField as one of its fields. Within that custom DictField, the child field is tasked with recording the dictionary key that it is the value of whenever serializer.save() is called. How would one go about knowing the key of the dictionary being deserialized when interpreting the internal value to be saved? class ChildField(Serializer): parent_key = CharField() def to_internal_value(self, data): # At this point, the likely candidate for the # key is self.field_value, but it is actually '' # data['parent_key'] = ??? return super().to_internal_value(data) class ParentField(DictField): child = ChildField() Assume the data being deserialized is the following: { "the_dictionary": { "key_we_want_to_save": { "arbitrary_other_child_data": True } } } -
Django if statements in forms
I am trying to allow a user to upload a file of unknown type through a form and then save it to a folder depending on the type of file it is. I was hoping I could use 'if' statements, but I can't make them work inside the form. I currently just have direct upload paths: class Post(models.Model): Priority_Upload = models.FileField(default='priority', upload_to='priority/', blank=True, null=True) title = models.CharField(max_length=100) content = models.FileField(default='text', upload_to='text/', blank=True, null=True) image = models.ImageField(default='default', upload_to='images/', blank=True, null=True) video = models.FileField(default='video', upload_to='videos/',blank=True, null=True) large_video = models.FileField(default='large_video', upload_to='large_video/', blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) # user owns the post, but post doesn't own the user. author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I'd like to do something like this, but it doesn't work: class Post(models.Model): Priority_Upload = models.FileField(default='priority', upload_to='priority/', blank=True, null=True) title = models.CharField(max_length=100) if(*image ends in .txt*) content = models.FileField(default='text', upload_to='text/', blank=True, null=True) if(*image ends in .png*) image = models.ImageField(default='default', upload_to='images/', blank=True, null=True) ... is there any way to do this? -
Problems running the app locally with heroku and django
I'm trying to use my project locally to do some migrations since I was using heroku, but to migrate I need the local environment. Suddenly I got these errors whenever I use: python manage.py collectstatic and python manage.py runserver I already have my .env file with its variables, the SECRET_KEY and DEBUG. What I did notice is that in the file of settings, the config marks it in red from decouple import config I don't know where to start or how to translate them. -
How can I package my Django project with a server software so that it is ready to run on any machine?
I want to share the project to multiple clients so that they can use it on their own local networks without doing a lot of work. So somehow packaging the Django project along with a secure server software together so that it easily can be run on any machine would be nice. -
Escape single curly brace in Django template
I am looking to generate a string like \usepackage{mypackage} from a Django template. Suppose there is a variable package.name in the context how can I generate this? Firstly I tried, \usepackage{{{package.name}}} but that throws TemplateSyntaxError Then I tried \usepackage{ {{package.name}} } which works but has the two spaces in the output, ie, \usepackage{ mypackage } Is there an easy way to generate this string with Django template engine? -
Django default image not saving
I am having an issue while saving a default image whenever I am not uploading an image in ImageField. I can't understand what I am doing wrong, for me it seems everything ok but couldn't find where the bug is. models.py class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) date_of_birth = models.DateField() fiscal_code = models.CharField(max_length=50) phone = models.CharField(max_length=50) license = models.ForeignKey( License, on_delete=models.CASCADE, blank=True, null=True) picture = models.ImageField( blank=True, null=True, default='default.png') id_card = models.ForeignKey( IDCard, on_delete=models.CASCADE, blank=True, null=True) address = models.CharField(max_length=100) cap = models.CharField(max_length=10) city = models.CharField(max_length=100) province = models.CharField(max_length=100) country = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py def create_student(request): context = { } if request.method == 'POST': username = request.POST.get('username') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') date_of_birth = request.POST.get('date_of_birth') email = request.POST.get('email') phone = request.POST.get('phone') password = request.POST.get('password') address = request.POST.get('address') cap = request.POST.get('cap') province = request.POST.get('province') country = request.POST.get('country') fiscal_code = request.POST.get('fiscal_code') id_number = request.POST.get('id_number') expire_date = request.POST.get('expire_date') picture = request.FILES.get('picture') id_image = request.FILES.get('id_image') # fs = FileSystemStorage() # filename = fs.save(picture.name, picture) # profile_pic_url = fs.url(filename) # filename2 = fs.save(id_image.name, id_image) # id_image_url = fs.url(filename2) try: user = CustomUser.objects.create_user( username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=3) user.student.address = address user.student.date_of_birth = date_of_birth user.student.cap = cap user.student.province = province … -
new locale not redirecting properly
I have a basic django cms running with lots of localised content. I have been assigned to add few more languages before content can take over. here is a sample english url: <domain>/en/myhelp/ this is the sample menu which is supposed to render the menu dropdown: <body> {% cms_toolbar %} <div class="container faq-main main-block"> <div class="select-wrapper"> <select name="language" id="faq-lang" class="lang-btn hide"> <option value="en">English</option> <option value="hi">हिंदी</option> <option value="mr">मराठी</option> <option value="te">తెలుగు</option> <option value="ta">தமிழ்</option> <option value="kn">ಕನ್ನಡ</option> <option value="bn">বাংলা</option> <option value="ml">മലയാള൦</option> <option value="gu">ગુજરાતી</option> </select> </div> {% block content %}{% endblock content %} {% block contact %}{% endblock contact %} {% block actions %}{% endblock actions %} </div> {% render_bundle 'faq' 'js' %} {% render_block "js" %} </body> any language selected from menu dropdown updates the url accordingly. for example on selecting mr, url mentioned above would change to: <domain>/mr/myhelp/ All good so far. Now i have added 2 more langs in this menu: <option value="od">ଓଡିଆ</option> <option value="as">অসমীয়া</option> Problem is that when i select od / as from menu, url changes to: <domain>/en/od/myhelp/ <domain>/en/as/myhelp/ basically, en is not removed from url locale causing page not found error. Any help or indication in right direction to correctly add this locale is appreciated. version: django-cms: 3.7.1 Django: … -
Django admin login SSL_do_handshake() failed
I get following in nginx-error log while logging in to admin page of django website 2022/01/28 17:04:50 [crit] 22184#22184: *263 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 107.178.232.184, server: 0.0.0.0:443 2022/01/28 17:08:12 [crit] 22184#22184: *277 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 107.178.239.221, server: 0.0.0.0:443 2022/01/28 17:08:30 [crit] 22184#22184: *288 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 107.178.232.251, server: 0.0.0.0:443 2022/01/28 17:10:09 [crit] 22184#22184: *302 SSL_do_handshake() failed (SSL: error:14201044:SSL routines:tls_choose_sigalg:internal error) while SSL handshaking, client: 45.56.98.215, server: 0.0.0.0:443 2022/01/28 17:28:03 [crit] 22184#22184: *344 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 165.227.140.0, server: 0.0.0.0:443 One possible reason is I do not have the secret key I used while making the django project as I lost the .env file. I used this answer to generate a secret key and to store in the .env file. Could this be the reason, or is there some other reason? -
Updating is_issued in Book model after adding a book in Issued. Django restframework
This is models.py from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) is_issued = models.BooleanField(default=False) isbn = models.CharField(max_length=100) def __str__(self): return self.title class IssuedBooks(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) issued_to = models.CharField(max_length=100) issued_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.book.title viewsets.py from rest_framework import viewsets from .models import Book, IssuedBooks from .serializers import BookSerializer, IssuedBooksSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer class IssuedBooksViewSet(viewsets.ModelViewSet): queryset = IssuedBooks.objects.all() serializer_class = IssuedBooksSerializer # Add book to IssuedBooks and update book's is_issued field # Also be able to issue books when is_issued is false I assume the solution has something to do with the viewsets. It basically needs to have create and delete methods for Issuedbooks route while also updating and referencing Book model. -
ERRORS: inside.UserProfile.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
I am a beginner in Django. I am trying to build an app with user authentication. However I want extra fields like country and phone number, and I don't want any username field (I want the phone number to act as the username), so I built a custom user class. There are questions that have already been asked that have the same error, but they are not exactly relevant to my use case and the solutions don't work for me. models.py: from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser from django.conf import settings from django_countries.fields import CountryField # Create your models here. class UserProfile(AbstractBaseUser): user = models.OneToOneField(User, on_delete = models.DO_NOTHING) phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False) country = CountryField() uid = models.UUIDField( default = None, blank = True, null = True, unique = True, ) USERNAME_FIELD = "uid" REQUIRED_FIELDS = ['phone_number', 'country'] forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile from django_countries.fields import CountryField # Create your forms here.. class NewUserForm(UserCreationForm): phone_number = forms.RegexField(max_length = 16, regex = r'^\+?1?\d{9,15}$') country = CountryField() class Meta: model = UserProfile fields = … -
django-filter and django custom pagination with ModelViewSet
I implemented a modelviewset with django-filter and django default pagination comnbined. Its working fine when I use either django-filter or django pagination. But when they are used simultaneously then I am getting duplicate results in response. So whats the correct way to use pagination in django-filter with CBV? class TableMetaView(ModelViewSet): """ This will be used to create new tables. You require to add the table fields in json request and also the job request associated with that table. If you want to create new table then pass CREATE NEW TABLE In response you will get the table list along with the job request for each tables """ serializer_class = TableMetaSerializer queryset = TableMeta.objects.all() renderer_classes = [JSONRenderer] filterset_fields = [ "schema_name", "type", "status", "grouping__name", "dataset__name", ] ordering_fields = ["created_on", "modified_on"] ordering = ["-modified_on"] pagination_class = StandardResultsSetPagination permission_classes = [ UserHasDatasetChangeAccess & IsTableEditable, ] def get_queryset(self): if getattr(self, "swagger_fake_view", False): # queryset just for schema generation metadata return TableMeta.objects.none() return TableMeta.objects.filter( dataset=get_object_or_404(DataSet, id=self.request.META.get(DATASET_ID, "")) ) -
Django get Browser of user
I am trying to get the browser of the current logged in user. To do it I put this in the template {{ request.headers.user_agent }} It works but the output is this: (even if i try it with something like edge browser) Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4692.99 Safari/537.36 Edg/96.0.1072.69 My settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ...... ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', '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', ] Based on the browser I want to display a different content in the HTML. What is the best way to get the exact browser? -
Django how to upload CSV file using Form to populate postgres database and display all items in browser
Django 3.2.1, Python 3.6, Postgres database I am writing a small Django app that will use the browser to import products from an uploaded csv file via a Form and populate the database. I currently have the app set up so that users can manually add, edit, or delete individual products. These get saved to the database properly. However, I also want an option where a user can upload a csv with many thousands of products using a Django Form. I have written the backend logic for the app using Custom Management Commands and have read the docs but am still really unclear about how to achieve this using Forms while maintaining full functionality. I have tried many variations on using forms and completed the tutorials on Django's site, but have not been successful at actually getting the file to upload via Form, parse all lines correctly, save to database, and display all newly saved items at /show_products alongside where the products that have been manually added are displayed. Example of the csv file: name,sku,description Brian James,skus-will-look-like-this,The products will have various descriptions. And multiple lines too. Here is an example of my backend code that can upload a local csv … -
Structure of models to store a subset of choices to be available dependent on row being edited
I'm building a site that tracks parts, these part belong to a subsection of project, denoted by section codes. I want to be able to limit the choices of codes based on which project the part belongs to, but not sure the best way to store a list of acceptable codes. I started with: class Project(models.Model): name = models.CharField(max_length=40) number = models.IntegerField() class Section(models.Model): code = CharField(max_length=1) class Part(models.Model): number = models.IntegerField() project = models.ForeignKey(Project, on_delete=models.PROTECT) section = models.ForeignKey(Section, on_delete=models.PROTECT) The problem with this is that all parts then get to choose from the same list of section codes. -
models.py order of the models gives NameError: name 'Category/Post' is not defined
I'm new to Django so this is probably a dumb question but, when I put the class Category model above the class Post model I get an NameError: name 'Post' is not defined error. but when I try to put class Category model underneath the Post model (as in the code here) I get categories = models.ManyToManyField(Category) NameError: name 'Category' is not defined error. models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) #if is deleted than delete their posts location = models.CharField(max_length=100, default="") tags = TaggableManager() likes = models.ManyToManyField(User, related_name='blog_posts') categories = models.ManyToManyField(Category) def total_likes(self): return self.likes.count() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): post = models.ForeignKey(Post, related_name="categories") name = models.CharField(max_length=20) def __str__(self): return self.name admin.py from django.contrib import admin from .models import Post, Comment, Category #, Konum # Register your models here. admin.site.register(Post) admin.site.register(Comment) admin.site.register(Category) #admin.site.register(Konum) -
Django href for html
How i can make link to this urls.py? I tried to pass the link through all the methods I know but they don't work and gave an error path('category/<slug:gender_slug>/<slug:category_slug>/', views.StuffCategory.as_view(), name='category'), html: {% get_genders as genders %} {% for gender in genders %} <li> <!-- First Tier Drop Down --> <label for="drop-2" class="toggle">Категории <span class="fa fa-angle-down" aria-hidden="true"></span> </label> <a href="/">{{ gender }} <span class="fa fa-angle-down" aria-hidden="true"></span></a> <input type="checkbox" id="drop-2"> <ul> {% get_categories as categories %} {% for category in categories %} <li><a href="/">{{category.name}}</a></li> {% endfor %} </ul> </li> {% endfor %} views.py class StuffCategory(ListView): model = Stuff template_name = 'shop/shop.html' context_object_name = 'stuffs' def get_queryset(self): queryset = Stuff.objects.filter(draft=False) if self.kwargs.get('category_slug'): queryset = queryset.filter(category__slug=self.kwargs['category_slug']) if self.kwargs.get('gender_slug'): queryset = queryset.filter(gender__slug=self.kwargs['gender_slug']) return queryset