Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Switching between currencies and displaying the corresponding price in Django template
There is Product model with price field in my Django app. Base currency is USD. There are couple of Product instances rendering in the template at the same time. I would like to add ability to switch between different currencies and render a corresponding price in template, but i don't know how. I've read Django-money app documentation and tried to implement currency exchange using FixerBackend and fixer free account. But i failed. Could you please share some experience from your projects and give some tips which way to implement this idea is the easiest and best, cause i'm stack.. -
Django: Update an object form form
I'm trying to make my view to update an existing object, filling its attrs with form data. I found the syntaxis for this: Auxi.objects.filter(id=auxi).update(name='The new name', age=23, role='The new role') But the problem is that it will become too extensive for my object since it has 52 attrs and I just want to tell Django to replace all the values from my object with the data from form. I tried: form = AuxiForm(request.POST) item = form.save(commit=False) Auxi.objects.filter(id=auxi).update(form) and also Auxi.objects.filter(id=auxi).update(item) But it's saying update() takes 1 positional argument but 2 were given. Could someone help me please? Sorry if it's a duplicate post, I already tried to find it somewhere but I couldn't. -
How to access tables from a different schema in oracle 11g using django?
I have a user named mi_abc in oracle 11g. The user do not have any table in the database but has access to all the tables in another schema sch_abc. When I run a normal select query from sqldeveloper on the sch_abc schema from mi_abc, it works perfectly fine, but when I use django, I am always getting the error:- django.db.utils.DatabaseError: ORA-00942: table or view does not exist I tried to set the db_table = sch_abc.tableName and also set db_table = tableName but both gives me the same error. Any clue how to resolve this? -
Django - name 'title' is not defined
Before a hour ago I started to make a web, with Django just started to practice with this guy here https://www.youtube.com/watch?v=qDwdMDQ8oX4 I'm following all his steps, but after doing some stuff, I've got error which says title is not defined in /about/. Here's my code from /about/. The code is equal to my other home page, but this one doesn't work. enter image description here <!DOCTYPE html> <html lang="en" dir="ltr"> <head> {% if title %} <title>Django BLog - {{ title }}</title> {% else %} <title>Django blog</title> {% endif %} </head> <body> </body> </html> -
Django login doesn't work, how can fix it?
I have login form in my project. When I write correct username and password it doesn't post my request and my browser area looks like that: http://127.0.0.1:8000/user/login/?csrfmiddlewaretoken=EukLSCRC5B25iBrDXqVsQ7iyF2FUUhgrldri2MIrb3IM8f4dMngo66tciJkmfNYt&username=admin&password=123 (Because my username:admin, pass:123) I tried change "form method" POST to post in html login template but doesn't work. And I deleted csrf_token but actually doesn't work again. forms.py class LoginForm(forms.Form): username = forms.CharField(label = "Username") password = forms.CharField(label = "Password", widget=forms.PasswordInput) views.py def loginUser(request): form = LoginForm(request.POST or None) context = { "form": form } if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username = username, password=password) if user is None: messages.info(request,"Username or Password is incorrect! Try again.") return render(request,"login.html", context) messages.success(request,"Login successful! Welcome honey.") login(request,user) return redirect("index") return render(request,"login.html",context) urls.py app_name = "user" urlpatterns = [ path('register/',views.register, name ="register"), path('login/',views.loginUser, name ="login"), path('logout/',views.logoutUser, name ="logout"), ] login.html {% extends "layout.html" %} {% block body %} {% load crispy_forms_tags %} <div class="row"> <div class="col-md-6 offset-md-3"> <h3>Login</h3> <hr> <form method = "post"> {% csrf_token %} {{form|crispy}} <button type = "submit" class = "btn btn-danger">Sign In</button> </form> </div> </div> {% endblock %} Browser area shows: http://127.0.0.1:8000/user/login/?csrfmiddlewaretoken=EukLSCRC5B25iBrDXqVsQ7iyF2FUUhgrldri2MIrb3IM8f4dMngo66tciJkmfNYt&username=admin&password=123 (Because my username:admin, pass:123) -
Django - create multiple elements of different model at once
I have 2 models with OneToOne relation between them. I want to create a single instance of each of them at once, to avoid 2 queries towards the server (which is a bit slower) class FilePath(models.Model): storage_path = models.CharField(max_length=100) date_created = ... class Image(models.Model): path = models.OneToOneField(FilePath, on_delete=models.CASCADE) width = models.IntegerField() # I want these queries to be combined to a single server access file_path = FilePath.objects.create(storage_path=r"/images/1234.jpg") image = Image.objects.create(path=file_path, width=250) -
Unable to bind event to datetimepicker in javascript
I'm running django-bootstrap-datepicker-plus==3.0.5. I'm attempting to bind an event to the datetimepicker so that that on a certain action, an attribute changes. The list of attributes that can be changed are found here: https://eonasdan.github.io/bootstrap-datetimepicker/ As the page above shows, I should just be able to use the following code to set inline to true (note: I'm able to set this attribute to true on the initialization of the form in forms.py and it works fine). $(document).ready(function() { $('#datetimepicker').datetimepicker({ inline: true, }); }); Unfortunately, this code doesn't do anything. Should I be using '.datetimepicker' in the code above? Is there anything different about the django version of this datetimepicker that is causing this code not to work? Not sure if this makes a difference, but the following code does work: $('.input-group').on("dp.change", function(e){ console.log('There was a change to the date'); }); Thanks for the help! -
Django like user
Im trying to include like button in User detail page. But its not working. urly.py added url(r'^like/$', views.like, name='liked_user'), models.py class User(AbstractUser): name = models.CharField(_("User's name"), blank=True, max_length=255) phone = models.CharField(_('Contact phone'), max_length=10, null=True, blank=True) picture = models.ImageField( _('Profile picture'), upload_to='profile_pics/', null=True, blank=True) zip_code = models.CharField(_('Zip Code'), max_length=10, null=True, blank=True) location = models.CharField( _('Location'), max_length=50, null=True, blank=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="liked_user") views.py @login_required @ajax_required @require_http_methods(["POST"]) def like(request): if request.method == 'POST': user = request.user slug = request.POST.get('slug', None) liked_user = get_object_or_404(User, slug=slug) if liked_user.likes.filter(id=user.id).exists(): # user has already liked this company # remove like/user liked_user.likes.remove(user) message = 'You disliked this' else: # add a new like for a company liked_user.likes.add(user) message = 'You liked this' ctx = {'likes_count': liked_user.total_likes, 'message': message} return HttpResponse(json.dumps(ctx), content_type='application/json') user detail.html <input type="button" id="like" name="{{ liked_user_slug }}" value="like" /> <script> $('#like').click(function(){ $.ajax({ type: "POST", url: "{% url 'like' %}", data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { alert(response.message); alert('likes count is now ' + response.likes_count); }, error: function(rs, e) { alert(rs.responseText); } }); }) </script> But when I try to open the user detail page, I get the error 'like' not found. 'like' is not a valid view function or … -
How to filter objects by slug instead id
I have an Event model, serializer, viewset, and a Tag model, serializer, viewset. I want filter Events by tags_name. But it's only possible to filter it by tag_id In tag serializer I've set lookup_field in TagSerializer. Option when I 'filter_field = (tags__name)' is not appropriate, because last GET parameter change previous class EventSerializer(serializers.ModelSerializer): from accounts.api.serializers import ShortUserSerializer tags = serializers.SlugRelatedField( many=True, queryset=Tag.objects.all(), slug_field='name' ) members_count = serializers.SerializerMethodField() author = ShortUserSerializer() max_members = serializers.IntegerField(required=False, default=-1) class Meta: model = Event fields = ['id', 'name', 'description', 'time_begins', 'author', 'members_count', 'max_members', 'tags', 'avatar', 'date_expire', 'city', 'country', 'geo'] ... class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' lookup_field = 'name' extra_kwargs = { 'url': {'lookup_field': 'name'} } ... class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.all() serializer_class = EventSerializer http_method_names = ['get', 'patch'] filter_backends = (filters.SearchFilter, DjangoFilterBackend,) search_fields = ('name', 'author__username', ) filter_fields = ('tags') I receive result with this: `localhost:8000/events/?tags=1&tags=2` And it actually works But I need: `localhost:8000/events/?tags=#fun&tags=#movie` -
Django ModelFormSet object changes type on post
I'm converting a page from using manually rendered post/get functions to one using class-based views. I am attempting to move towards using all of Django's built-in functionality. But I'm encountering a confusing error where the ModelFormSet object is not the right type when the form is posted. I have this form: class AssignmentDatesForm(forms.ModelForm): class Meta: model = AssignmentDates fields = [ 'assignment_name', 'start_date', 'due_date', 'end_date', ] widgets = { 'start_date' : forms.DateInput(format = '%m/%d/%Y', attrs ={ 'class' : 'datepicker'}), 'due_date' : forms.DateInput(format = '%m/%d/%Y', attrs ={ 'class' : 'datepicker' }), 'end_date' : forms.DateInput(format = '%m/%d/%Y', attrs ={ 'class' : 'datepicker' }),} def clean(self): logging.warning("Clean function") logging.warning("start_date: " + str(start_date)) logging.warning("due_date: " + str(due_date)) logging.warning("end_date: " + str(end_date)) # Actual validation logic here And create the ModelFormSet using modelformset_factory: AssignmentDatesFormSet = forms.modelformset_factory( model = AssignmentDates, form = AssignmentDatesForm, extra = 0, ) Here is the view, shortened for brevity: class EditDueDates(CurrentUserMixin, ModelFormSetView): model = AssignmentDates page_title = 'Edit Due Dates' success_message = "Dates updated successfully!" add_button_title = "Add Button Title" form = AssignmentDatesForm formset = AssignmentDatesFormSet template_name = "edit_due_dates.html" sidebar_group = ['scaffold', 'edit_due_dates'] columns = [ ('Assignment Name', 'assignment_name'), ('Start Date', 'start_date'), ('Due Date', 'due_date'), ('End Date', 'end_date'), ] fields = … -
Django check if article is paid or not
i want to check if a post has been paid or not. therefor i created a unique_together constrain between paying_user, post_sell_multiple and post_sell_once class Post_Paid(models.Model): paying_user = models.ForeignKey(User, on_delete=models.CASCADE) post_sell_multiple = models.ForeignKey(Post_Sell_Multiple, on_delete=models.CASCADE) post_sell_once = models.ForeignKey(Post_Sell_Once, on_delete=models.CASCADE) status = StatusField() STATUS = Choices('Unpaid', 'Paid') paid_date = models.DateField(auto_now_add=True, null=True) def publish(self): self.paid_date = timezone.now() self.save() class Meta: unique_together = (("paying_user", "post_sell_multiple", "post_sell_once"),) My question now is how can i accomplish that each time a post_sell_multiple or post_sell_once object is created the status is "Unpaid" so that i can later set it to "Paid" at my views? thanks in advance -
Is there possibility to hook up static page to my webapp made in Django?
I have my webapp which is simple shop app and i want add to this app page that contain informations like short description about shop, contact to shop and address. And i want for that page to be static page. I dont think that i need to contain this informations in database. I Can make this page in html/css but i dont know how hook up this page to my app. my app main address is http://127.0.0.1:8000/shop and i want for this page to have adress http://127.0.0.1:8000/shop/About_firm. -
How do I configure multiple django applications to use the same database?
As I configure my Django applications to use containers I'm left with a problem as I try to separate my processes into smaller images. How can I break logic into smaller components that run in their own containers, yet access the same database? I realize that in a "true" microservices environment I'd want a different database for each service. However, consider a situation where I have a bit of logic that reads data from a database, and produces a CSV file. I'd like to break out that into a separate type of image, that contains only that logic and gets a special disk mount to write the file to. The rest of the applications remain stateless. So I'm left with needed two django applications, one that reads and writes data to its database, and another one that I can use to spin up and run reports against that same database. Option 1: Is that I keep using the same application, where the models have already been defined. I spin up one container for processing, and spin up another container of the same image for use for reporting. While this would work, it seems like it would be a better pattern … -
Django Blog Post Text Editor Deleting Leading Spaces
This seems to be a problem on all Django blog frameworks that I've come across, and I am currently experiencing it on Mezzanine's "Moderna" theme. When making a blog, in the contents section, if one pastes any text, it automatically loses leading spaces/tabs on each line. One cannot indent lines with the tab key either. Is there any way to keep the leading spaces in the text editor when pasting formatted text? -
Serialize foreign key's foreign key (DRF)
I have 3 levels of models: Question Session (contains a bunch of questions), Question and Answer. They all are connected via ForeignKey: class QuestionSession(models.Model): name = models.CharField(max_length=100) class Question(models.Model): description = models.CharField(max_length=400) question_type = models.CharField(max_length=50) answers = models.PositiveIntegerField(default=0) answers_to_close = models.PositiveIntegerField(default=3) answered = models.BooleanField(default=False) choices = models.CharField( max_length=1000, blank=True, null=True, default=None) question_session = models.ForeignKey( QuestionSession, on_delete=models.CASCADE, related_name='questions', blank=True, null=True, default=None ) class Answer(models.Model): question = models.ForeignKey( Question, related_name='answers_list', on_delete=models.CASCADE) answer = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) And my serializers.py: class QuestionSessionSerializer(serializers.ModelSerializer): project = ProjectSerializer() class Meta: model = QuestionSession fields = [ 'id', 'questions', 'project' ] class QuestionSerializer(serializers.ModelSerializer): question_session = QuestionSessionSerializer() class Meta: model = Question fields = [ 'id', 'description', 'question_type', 'created_at', 'answers', 'answers_to_close', 'answered', 'question_session', 'choices', 'answers_list' ] class AnswerSerializer(serializers.ModelSerializer): question = QuestionSerializer() class Meta: model = Answer fields = [ 'question', 'answer', 'created_at' ] I can easily get question objects from QuestionSession with: QuestionSession.objects.get(pk=1).questions.all() And I'm also able to get answers with the following: QuestionSession.objects.get(pk=1).questions.objects.get(pk=1).answers_list.all() But when I send this data through Response, it only sends answers' ids instead of objects. My view: def get(self, request, **kwargs): """Fetch a single session""" session_id = kwargs['session_id'] questions = QuestionSerializer( QuestionSession.objects.get( pk=session_id).questions.filter(answered=False), many=True ) return Response({ 'session': session_id, 'questions': questions.data }) … -
django-autofixture : can't create user model in DB
I'm trying to populate my database via command line with django-autofixture. I've populated some of my model but I can't populate the User model of Django. Here is what I've tried : manage.py loadtestdata django.contrib.auth.models.User:10 ----------------------------------------------------------- CommandError: Invalid argument: django.contrib.auth.models.User:10 Expected: app_label.ModelName:count (count must be a number) Is there a possibility to bypass the way the command line is parsed ? -
Django double post request after a Heroku application error
I was wondering if there is a way to prevent a double post request after an application error happens. I run a Django app on Heroku and sometimes when I hit a submit button, an application error occurs. I can't figure out why this happens, but that's another question ;-) When I refresh the application error page, I get redirected correctly, but the post request was done twice. Is there a way to prevent this double post? -
django-tables doesn't display foreign-key as link in gcbv ListView
I'm using django-tables2 to for a generic.listview. I have 3 models involved (shortened) GenericDevice which is inheriting from abstract class Device, Invoice which is a foreign key, and InvoiceSupplier which is a foreign key in Invoice. All classes have get_absolute_url defined. What I would like to do is to display the foreign key InvoiceSupplier in django-table as a link to the detailview of the object. #inventory/models.py from invoices.models import Invoice, Supplier, Manufacturer class Device(models.Model): serial_number = models.CharField( max_length=20, unique=True, validators=[digits_chars] ) inventory_number = models.CharField( max_length=20, unique=True, default='Update THIS!', validators=[digits_chars], ) invoice = models.ForeignKey( Invoice, on_delete= models.PROTECT, ) manufacturer = models.ForeignKey( Manufacturer, on_delete= models.PROTECT, ) class Meta: abstract = True class GenericDevice(Device): owner = models.ForeignKey( User, on_delete=models.PROTECT, null= True, blank = True, ) type = models.ForeignKey( DeviceType, related_query_name='generic_devices', default=6, on_delete=models.PROTECT, ) device = models.ForeignKey( NetworkDevice, on_delete=models.PROTECT, null=True, blank=True, ) #invoices/models.py class contact(models.Model): name = models.CharField( max_length=120, unique=True, help_text="Contact Name/Company Name", ) address = models.TextField( max_length=255, blank=True, ) phone_number = models.CharField( max_length=13, blank=True, ) emailaddress = models.EmailField( blank = False, unique=True, default='johdoe@changeme.com' ) class Meta: abstract = True class Supplier(contact): TIN = models.CharField( max_length=50, name='TIN', ) Description = models.TextField( null = True, ) class Invoice(models.Model): #If plural not corectly configured in admin(override) … -
Django error AssertionError: False is not true : Couldn't find 'href = "/boards/1/"' in response
I'm going through this Django tutorial building a board app. Can anyone tell where I've made my mistake please? I'm getting this error when I run my test: FAIL: test_new_topic_view_contains_link_back_to_board_topics_view (boards.tests. NewTopicTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Inetpub\wwwroot\myproject2\myproject2\boards\tests.py", line 73, in t est_new_topic_view_contains_link_back_to_board_topics_view self.assertContains(response, 'href = "{0}"'.format(board_topics_url)) File "C:\Inetpub\wwwroot\myproject2\venv_two\lib\site-packages\django\test\tes tcases.py", line 369, in assertContains self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr) AssertionError: False is not true : Couldn't find 'href = "/boards/1/"' in respo nse ---------------------------------------------------------------------- Ran 11 tests in 0.042s FAILED (failures=1) Destroying test database for alias 'default'... My test.py code for new topics: class NewTopicTests(TestCase): def setUp(self): Board.objects.create(name='Django', description='Django board') def test_new_topic_view_success_status_code(self): url = reverse('new_topic', kwargs={'pk':1}) response = self.client.get(url) self.assertEquals(response.status_code, 200) def test_new_topic_view_not_found_status_code(self): url = reverse('new_topic', kwargs={'pk':99}) response = self.client.get(url) self.assertEquals(response.status_code, 404) def test_new_topic_url_resolves_new_topic_view(self): view = resolve('/boards/1/new/') self.assertEquals(view.func, new_topic) def test_new_topic_view_contains_link_back_to_board_topics_view(self): new_topic_url = reverse('new_topic', kwargs={'pk': 1}) board_topics_url = reverse('board_topics', kwargs={'pk': 1}) response = self.client.get(new_topic_url) self.assertContains(response, 'href = "{0}"'.format(board_topics_url)) My urls.py file: from django.conf.urls import url from django.contrib import admin from boards import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^boards/(?P<pk>\d+)/$', views.board_topics, name='board_topics'), url(r'^boards/(?P<pk>\d+)/new/$', views.new_topic, name='new_topic'), url(r'^admin/', admin.site.urls), ] My views.py code: from django.shortcuts import render, get_object_or_404 from .models import Board def … -
How to fix 'ImportError' while working with multiple Django apps
I'm working with multiple apps in django and facing ImportError while running makemigrations command. The import statements are as follows, appwise: accounting/models.py from activity.models import HistoryModel activity/models.py from user_management.models import Customer, Merchant, PassIssued from accounting.models import ITMSCustomer user_management/models.py from accounting.models import Account, Transaction, Posting I'm sure that the order of apps listed in INSTALLED_APPS matter and the order is: 'user_management', 'accounting', 'activity', I get following error when I run makemigrations command: File "/home/abhishek/citycash/city-server/src/cityserver/user_management/models.py", line 4, in <module> from accounting.models import Account, Transaction, Posting File "/home/abhishek/citycash/city-server/src/cityserver/accounting/models.py", line 17, in <module> from activity.models import HistoryModel File "/home/abhishek/citycash/city-server/src/cityserver/activity/models.py", line 4, in <module> from user_management.models import Customer, Merchant, PassIssued ImportError: cannot import name 'Customer' I tried changing the order of apps in INSTALLED_APPS but I just ended up getting ImportError for different modules. I know this has something to do with the fact that all three apps are importing something from each other. How do I resolve this error? Any help is appreciated. Thanks in advance. -
Error related to parser.add_argument() when writing a custom django-admin command
I am writing a custom django-admin command which is the module named populate_db.py. Its location is the following within the django project: restaurant/ __init__.py models.py management/ commands/ _private.py populate_db.py tests.py views.py formDict.py The purpose of populate_db.py is to add objects to DB tables from an external dictionary {'key1':[values], 'key2': [values]}. The formDict.py forms a dictionary (d), and prints json.dumps(d) to stdout. Therefore, the dictionary is serialized to a JSON formatted string with double quotes and printed to stdout. When I run python restaurant/formDict.py while being in the directory where manage.py is located, the program is successfully completed and the JSON formatted string (converted dict) is printed to stdout. When I run the command python resturant/formDict.py | python manage.py populate_db while being in the directory where manage.py is located, I immediately get the following error: AttributeError: 'NoneType' object has no attribute 'items' Here's some parts of populate_db.py. This is a preliminary version which will be corrected and amended. from django.core.management.base import BaseCommand, CommandError from steakOUT.models import* import json class Command(BaseCommand): help = 'add objects to DB' def add_arguments(self, parser): parser.add_argument('dic',nargs='?', type=json.loads) def handle(self, *args, **options): dic=options['dic'] for k, v in dic.items(): for val in v: Why am I getting the mentioned … -
Django Admin Upload Image and Use the Image as Blog Background For Each Post
I am making a blog website and I need each new blog post to contain a different image as the background. The image is uploaded with the admin page, how do I reference the image in the HTML? Thanks for any help or recommendations! #models.py class Post(models.Model): title = models.CharField(max_length=50) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) image = models.FileField(upload_to='post_image', blank=True) body = models.TextField() class Meta: ordering = ['-created_date'] def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title #post_detail.html <header class="intro-header" style="background-image: {{ post.Post.image.url }} When a reference the url like this, I get a blank background for the post. Do I need to include anything in the settings? -
Creating a detail view with url getting data from get_context_data
I am trying to be able to push a string value, title from the book object selected to the url to display a detail view. I am missing some sort of logic here. views.py class IndexView(TemplateView): template_name = 'app/index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['book_data'] = Book.objects.all() return context urls.py urlpatterns = [ path('login/', views.LoginView.as_view(), name='login'), path('login/index/', views.IndexView.as_view(), name='index'), path('login/index/<str:key>', views.BookView.as_view(), name ='book_detail') index.html <ul> {% for book in book_data %} <li><a href="{% url 'book_detail' book.title"> {{book.title}} - {{book.name}} - {{book.author}}</a> </li> {% endfor %} </ul> I am routed to the proper view page but I'm not properly grabbing the title value and putting it in the url. this example comes back with this url http://127.0.0.1:8000/login/index/%7B%%20url%20'book_detail'%20book.title Also how would i be able to use the value in this url to display only data from the specific book in my detail view? so it would do something like this views.py class BookView(TemplateView): template_name = 'app/book_detail.html' def get_context_data(self, **kwargs): context = super(BookView, self).get_context_data(**kwargs) context['book_data'] = Book.objects.filter(title=<string from url>) return context -
In Django, how do you reference your project urls.py URLs?
I am making a django project with multiple apps inside of it. My directory structure is something like this: DjangoProject project_dir settings.py urls.py wsgi.py app1 urls.py ... app2 urls.py ... I understand how to access urls in my templates that are part of apps with {% url 'app1:url1' %} but that is because in my app urls.py files I can do something like this: app_name = 'app1' urlpatterns = [ path('', views.view1, name='home'), ] The project urls.py file seems to be different than app urls though. You cant give the project urls.py file an app_name so how is one supposed to reference project urls from inside a template? I have been just relying on relative links like this: <a href="/global_url"></a> but if I ever want to change the path of /global_url I have to go and update all my hard coded template urls. -
How to use Django FilterSet to filter MultiSelectField?
I've created a FilterSet using django_filters so users can filter through other user's profiles using filters such as city, age and gender. Those 3 fields in the FilterSet work fine, however I also want to filter by interest which is a MultiSelectField based on INTEREST_CHOICES. A user should be able to check multiple interests and filter based on those, in addition to the 3 fields listed above. I have been unable to get this to work. I managed to display an interest filter field however when a user selects one of the 4 interests from the dropdown box, the page does not return any matches, even if one of those interests is matched. I suspect it is because users select more than one interest, thus the interests are saved in a list and not individually, therefore the FilterSet can't find the standalone interest. If someone could look over my code and point me in the right direction, I would be most grateful. models.py class Profile(models.Model): INTEREST_CHOICES = ( ('FITNESS', 'Fitness'), ('CHURCH', 'Church'), ('VEGANISM', 'Veganism'), ('MOVIES', 'Movies'), ) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('X', 'Neither') ) user = models.OneToOneField(User, on_delete=models.CASCADE) interests = MultiSelectField(choices = INTEREST_CHOICES) city = models.CharField(max_length=30) age …