Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
provide rows by priority in django
I have the following model in django: class task(models.Model): admin = models.BooleanField() date = modesl.DateField() I am trying to achieve a filter which provides me with a query_set that prioritize if admin = True So assume I have these 3 rows : admin = True , date = 01-01-2019 admin = False , date = 01-01-2019 admin = False , date = 02-02-2019 The output of the query set will be : admin = True , date = 01-01-2019 admin = False , date = 02-02-2019 it should filter out the row with 01-01-2019 which admin=False because there is already an admin=True row which should take prioritization. I could do it by fetching all and removing it from the query_set myself, but want to make sure there is no other way of doing it before. -
How to created a nested dictionary with list values?
I have the follow two queryset: opus = Work_Music.objects.filter(composerwork__person=self.kwargs['pk'], level=0).order_by('date_completed') event = LifeEvent.objects.filter(person=self.kwargs['pk']).order_by('date_end') The first pulls the work of a composer and the second pulls his life events. I want to create a nested dictionary: The first level is keyed by year. The second level has two keys 'work' and 'life'. It should be a list of values because there could be multiple work and events in a given year. I have written following: # timeline = defaultdict(list) timeline = dict() for o in opus: if o.date_comp_f not in timeline: timeline[o.date_comp_f] = {} timeline[o.date_comp_f]['work'] = {} timeline[o.date_comp_f]['work'].append(o) else: timeline[o.date_comp_f]['work'].append(o) for e in event: if e.date_end_y not in timeline: timeline[e.date_end_y] = {} timeline[e.date_end_y]['life'] = {} timeline[e.date_end_y]['life'].append(e) else: timeline[e.date_end_y]['life'].append(e) timeline = dict(timeline) I also want to sort the first level key in chronological order. How do I do this? I keep getting Key errors. -
Clear all children subcategories of a selected (sub)category in a chained dependent dropdown combobox selection
I'm trying to implement chained dependent dropdown combobox selection, so you start with one combobox for main category and once you select main category, another <select> appears for selecting a subcategory, and so on until the innermost (most specific) subcategory is selected. Let's say that I have two main categories, Books and Shoes, so if I go Books -> Textbooks -> Primary school, then I decide to go for Shoes instead, four <selects>s would appear. Instead, I want to clear all children subcategories of a selected (sub)category (in this scenario, two <select>s (Textbooks and Primary school)) and leave the user to chose from only main category. Or, if I chose Books -> Literature, it should remove the Primary school/High school <select> and show subcategories of 'Literature'. Here is my jQuery code in a Django template: {% extends 'pages/base.html' %} {% block content %} <h1>Create a product</h1> <form method='POST' id='productForm' data-products-url="{% url 'products:ajax_load_categories' %}"> {{ form.as_p }} </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> var $r_ = function() { var url = $("#productForm").attr("data-products-url"); var categoryId = $(this).val(); $.ajax({ url: url, data: { 'category': categoryId }, success: function (data) { if (data != 'leaf_node') { $(".subcategories").append(data); } $('select').change($r_); } }); } //end of $r_ $('select').change($r_); … -
how to create a proportional (pre-define boundaries) colour bar with python bokeh library
I would like to plot a graph with a proportional colour bar on the right like graph 1, but with bokeh rather than matplotlib: The matplotlib version is: proportional (pre-define boundaries) colour bar using matplotlib colors.BoundaryNorm(bounds, cmap.N) But my current bokeh version is looks like this: right hand side colour bar not proportional, although I have given ticker boundaries Please see my bokeh version code. Although I have given ticker boundaries, but the colour bar still not proportional. ticker = FixedTicker(ticks=bounds) bounds = [0, 5, 25, 75, 95,100] color_bar = ColorBar(color_mapper=mapper, major_label_text_font_size='5pt', ticker=ticker, formatter=PrintfTickFormatter(format='%d%%'), label_standoff=6, border_line_color=None, location=(0, 0)) The reason I use bokeh is because I would like to use it with Django and have the tools option within the bokeh library. Please give suggestions. Thanks in advance, -
When doing GET request to localhost:121/logout I get "accounts.views.logout didn't return an HttpResponse object". Is this an issue?
When I go to localhost:121/logout I get The view accounts.views.logout didn't return an HttpResponse object. It returned None instead. Should I modify my code, to deal with this, or is this not an issue? My logout is working fine. Do I have to list logout in my urls.py? views.py def logout(request): if request.method == "POST": auth.logout(request) return redirect('login') urls.py from django.urls import path from . import views urlpatterns = [ path('register/', views.register, name='register'), path('logout', views.logout, name='logout'), path('', views.login, name='login'), ] profile.html <ul> <li> <a class="dropdown-item" href="javascript:{document.getElementById('logout').submit()}">Logout</a> </li> <form id="logout" action="{% url 'logout' %}" method="POST"> {% csrf_token %} <input type="hidden"> </form> </ul> -
URL doesn't have a redirection to https
I have applications in Django 2.2 on the server where nginx is. My application can work under several subdomains, but it is the user who chooses what domain it will be, for example: first.mydomain.com test.mydomain.com city.mydomain.com My problem is that these subdomains work under https but only when I type in the whole address: https://test.mydomain.com. However, it does not work when I type in the address itself: test.mydomain.com - here I got nginx page with "Welcome to nginx!" I tried with nginx and redirects - no result. My nginx settings server { listen 80; server_name ~^(?<subdomain>.+)\.mydomain\.com$; return 301 https://$subdomain.mydomin.com$request_uri; } How can I get a redirection to https after typing only test.mydomain.com? -
Use DRF permissions in django view
I have several DRF permission classes for my rest api like this: class CanAccessImage(permissions.BasePermission): message = _("You don't have permission for this action.") def has_object_permission(self, request, view, obj): if obj.user == request.user: return True else: return False Can I use this permissions in Django views? -
Django - The 'image' attribute has no file associated with it
I had to change the save method so that a user can register without a profile image. Now I get this same error that no file was associated with the login. As per traceback it validates the form and tries to saves the image? It should not check for the image. Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/views.py" in dispatch 90. return super(LoginView, self).dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py" in post 183. return self.form_valid(form) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/views.py" in form_valid 119. auth_login(self.request, … -
Travis CI test fail as if no database
I have tested my software, which is a Django app, locally using nose. Running python manage.py test works as expected, but uploading my app onto travis fails. dist: xenial # required for Python >= 3.7 language: python python: - "3.7" env: - CM_DATABASE_NAME='cm_db.sqlite3' CM_DATABASE_USERS_NAME='messenger_users_db.sqlite3' CM_DATABASE_ENGINE='django.db.backends.sqlite3' CM_DATABASE_USER='' CM_DATABASE_PASSWORD='' \ CM_DATABASE_HOST='' CM_DATABASE_PORT='' CM_DATABASE_USERS_ENGINE='django.db.backends.sqlite3' install: - pip install -r requirements.txt - pip install . # command to run tests script: - python manage.py makemigrations && python manage.py migrate auth && python manage.py migrate --database=default && python manage.py migrate --database=messenger_users_db && python manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'adminpass')" && python manage.py test --keepdb # https://stackoverflow.com/questions/6244382/how-to-automate-createsuperuser-on-django # Push the results back to codecov after_success: - codecov The branch in specific is tester. https://travis-ci.com/afinidata2019/afinidata-content-manager -
Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/$']
I've been all day struggling with this issue in my starting Django Course. I'm getting this error: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P[0-9]+)/$'] Below you can see my code. I wish someone could give me a hand on this. Thanks a lot. views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponse from django.http import Http404 from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} print ("esto es CONTEXT: ") print (context) print(request) print ("FIN DE CONTEXT") return render(request, 'polls/index.html', context) # Create your views here. def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] index.html `<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> ` -
Using Django sqlite in web application any security precautions
I've hidden the secret key/admin location/security precautions for superuser. Any security precautions for the securing the base sqlite DB in Django web application? Any general DB Django security tips? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } -
Can you do additional math on an aggregate value in a Django queryset
I am trying to avoid repeat aggregating on a value I have already calculated. I am already getting an annual total, but I also want a quarterly total What would work: props_obj = PropertiesUsers.objects\ .aggregate(returns_coc_a=Sum(F('subscribe_amount') * (F('deal_coc') / Value(100))), returns_coc_q=Sum(F('subscribe_amount') * (F('deal_coc') / Value(100))) / Value(4)) What I am trying to find out if/how I can do (reuse the annual amount): props_obj = PropertiesUsers.objects\ .aggregate(returns_coc_a=Sum(F('subscribe_amount') * (F('deal_coc') / Value(100))), returns_coc_q=returns_coc_a / Value(4)) -
How can I make an immutable created_at field in MySQL
I'm trying to have an immutable field(created_at) and be able to update it(updated_at) without altering the original created_at field. This is a django project if that matters -
Django: How to prevent duplicates when using "Signals" with "dispatch_uid"?
Hello i am testing Django User/ AUTH nesting with other models. i made a simple model for my User called MyProfil. Everytime a new User is registered a new MyProfil object will created automatically and linked to the specific User. models.py #-- create a MyProfil.object for new user @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_myprofil(sender, instance, created, **kwargs): if created: MyProfil.objects.create(owner=instance) class MyProfil(models.Model): # --- head id = models.UUIDField(primary_key=True, default=uuid4, editable=False) oblink = models.UUIDField(unique=True, default=uuid4, editable=False) owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # --- body aboutme = models.TextField(max_length=300, blank=True) city = models.TextField(max_length=300, blank=True) Question The Django Doc mentioned to usedispatch_uid to prevent that maybe duplicates will send. Unfortunately i don´t really understand how to apply dispatch_uid so ended up with this approach for receiver. models.py <...> from django.core.signals import request_finished #-- create a MyProfil.object for new user @receiver(post_save, sender=settings.AUTH_USER_MODEL, dispatch_uid="my_unique_identifier") def create_myprofil(sender, instance, created, **kwargs): if created: MyProfil.objects.create(owner=instance) request_finished.connect(create_myprofil, dispatch_uid="my_unique_identifier") <...> So my question is if this the right way to apply dispatch_uid ? -
Attach a callback to a newly created <select>
I'm trying to implement chained dependent dropdown combobox selection, so you start with one combobox for main category and once you select main category, another <select> appears to select a subcategory, and so on until the innermost (most specific) category is selected. The code I have currently only works for one subcategory (direct children), how can I make it work for other levels too? So, I need to attach an onChange callback to a newly created <select> somehow. This is jQuery code in my Django template: {% extends 'pages/base.html' %} {% block content %} <h1>Create a product</h1> <form method='POST' id='productForm' data-products-url="{% url 'products:ajax_load_categories' %}"> {{ form.as_p }} </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("select").change(function () { var url = $("#productForm").attr("data-products-url"); var categoryId = $(this).val(); $.ajax({ url: url, data: { 'category': categoryId }, success: function (data) { $("#productForm").append(data); } }); }); </script> {% endblock %} Here is my view: def load_categories(request): category_id = request.GET.get('category') subcategories = Category.objects.get(id=category_id).get_children() return render(request, 'products/category_dropdown_list_options.html', {'subcategories': subcategories}) products/category_dropdown_list_options.html <select id="select_{{ subcategories.first.get_level }}"> <option value="">---------</option> {% for subcategory in subcategories %} <option value="{{ subcategory.pk }}">{{ subcategory.name }}</option> {% endfor %} </select> Here is my urls.py: app_name = 'products' urlpatterns = [ path('create/', product_create_view, name='product-create'), path('ajax/load-categories/', load_categories, name='ajax_load_categories') ] -
How to calculate a rank in a property decorator in Django model when the rank is based on another property decorator
I am newbie coder and very new to Django/Python. I am building an application that consolidates results for a rowing race. I have the following models in models.py. class Crew(models.Model): name = models.CharField(max_length=50) id = models.IntegerField(primary_key=True) composite_code = models.CharField(max_length=10, blank=True, null=True) club = models.ForeignKey(Club, related_name='crews', on_delete=models.CASCADE) rowing_CRI = models.IntegerField(blank=True, null=True) rowing_CRI_max = models.IntegerField(blank=True, null=True) sculling_CRI = models.IntegerField(blank=True, null=True) sculling_CRI_max = models.IntegerField(blank=True, null=True) event = models.ForeignKey(Event, related_name='crews', on_delete=models.CASCADE) status = models.CharField(max_length=20) penalty = models.IntegerField(default=0) handicap = models.IntegerField(default=0) manual_override_minutes = models.IntegerField(default=0) manual_override_seconds = models.IntegerField(default=0) manual_override_hundredths_seconds = models.IntegerField(default=0) bib_number = models.IntegerField(blank=True, null=True) band = models.ForeignKey(Band, related_name='bands', on_delete=models.CASCADE, blank=True, null=True) @property def raw_time(self): if len(self.times.filter(tap='Start')) > 1 or len(self.times.filter(tap='Finish')) > 1: return 0 start = self.times.get(tap='Start').time_tap end = self.times.get(tap='Finish').time_tap return end - start @property def race_time(self): # The race time can include the penalty as by default it is 0 return self.raw_time + self.penalty*1000 @property def event_band(self): if not self.band: return self.event.name return str(self.event.name) + ' ' + str(self.band.name) class RaceTime(models.Model): sequence = models.IntegerField() bib_number = models.IntegerField(blank=True, null=True,) tap = models.CharField(max_length=10) time_tap = models.BigIntegerField() crew = models.ForeignKey(Crew, related_name='times', on_delete=models.SET_NULL, blank=True, null=True,) I want to create two additional properties. One that will rank a crew by race_time across all crews and one that will rank … -
I get NoReverseMatch error when trying to pass data from a form to database in Django
I am new to Django and i wrote some code which is supposed to take some data from a form in orderr.html and pass it to the data base ( the app is called order) orderr.html <form action="{% url "order:createpost" %}" method="post"> **this is where i get the error** {% csrf_token %} First name: <input type="text" name="first_name"/><br/> Last name: <input type="text" name="last_name"/><br/> Address: <input type="text" name="address"/><br/> <input type="submit" value="Send"/> views.py @require_POST def createpost(request): if request.method == 'POST': if request.POST.get('first_name') and request.POST.get('last_name') and request.POST.get('address'): post = buyerData() post.first_name = request.POST.get('first_name') post.last_name = request.POST.get('last_name') post.address = request.POST.get('address') post.save() return render(request, 'order/orderr.html') else: return render(request, 'order/orderr.html') urls.py from django.conf.urls import url from order import views from django.urls import path app_name = 'order' urlpatterns = [ path('order_page/', views.OrderPage, name='order_page'), ] Do you have any idea why the error says that 'Reverse for 'createpost' not found' -
How to create a dict with two sub list?
I am trying to loop through two querysets with keys based on dates in the set. Each date has two types of items: Life events and work. The dict should look like this: Timeline['1980']['event'] = "He was born" Timeline['1992']['work'] = "Symphony No. 1" Timeline['1993']['event'] = "He was married" Timeline['1993']['work'] = "Symphony No. 2" How do I create this dictionary? -
Readonly don'y save on database - Django
I am creating a form with Django, and the result of one input I am putting in another input that is like "readonly". I added everything in models.py and forms.py, but it is not creating readonly columns in the database. To leave as readonly I used JavaScript by setting .readOnly to true. Does anyone know what the problem may be? -
MultipleObjectsReturned error in Django but I want multiple objects to be returned
Using Django REST framework I created an url which maps to a page with a JSON file containing all the objects in my database. I want to do the same but instead of showing all the objects I want only the objects that match a specific category (category is an attribute in my model). I have urls that show a JSON files with a single object in it (using the pk attribute) but when I try to do the same thing with category instead of pk I get a MultipleObjectsReturned error. I'm just sperimenting with the REST framework, I tried using different views and class based views solving nothing. Any hint or suggestion is really appreciated thanks. # models.py class Hardware(models.Model): name = models.CharField(max_length=25) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) def get_api_url(self): return api_reverse("category-api-postings:post-rud", kwargs={'category': self.category}) #views.py class HardwareListView(generics.ListCreateAPIView): pass lookup_field = 'pk' serializer_class = HardwareSerializer def get_queryset(self): query = self.request.GET.get("q") qs = Hardware.objects.all() if query is not None: qs = qs.filter(Q(title__icontains=query) | Q(content__icontains=query)).distinct() return qs class HardwareRudView(generics.RetrieveUpdateDestroyAPIView): pass lookup_field = 'category' serializer_class = HardwareSerializer def get_queryset(self): return Hardware.objects.all() #urls.py app_name = 'category-api-postings' urlpatterns = [ path('', exercise_view), path('list-api/', HardwareListView.as_view(), name='all'), path('list-api/<str:category>/', HardwareRudView.as_view(), name='post-rud') #serializer.py class HardwareSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField(read_only=True) class Meta: … -
Django - Type Error: save() got an unexpected keyword argument 'force_insert'
I get this error when I try to register a new user. Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py" in post 183. return self.form_valid(form) File "/home/django/django_project/accounts/views.py" in form_valid 34. new_user = User.objects.create(username=username, email=email) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in create 394. obj.save(force_insert=True, using=self.db) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/base_user.py" in save 80. super(AbstractBaseUser, self).save(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save 808. force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base 848. update_fields=update_fields, raw=raw, using=using, File "/usr/local/lib/python2.7/dist-packages/django/dispatch/dispatcher.py" in send 193. for receiver in self._live_receivers(sender) File "/home/django/django_project/accounts/models.py" in post_save_user_receiver 150. new_profile = UserProfile.objects.get_or_create(user=instance) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get_or_create 466. return self._create_object_from_params(lookup, params) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in _create_object_from_params 500. obj = self.create(**params) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in create 394. obj.save(force_insert=True, using=self.db) Exception Type: TypeError at /register/ Exception Value: save() got an unexpected keyword argument 'force_insert' I added a form for the user to upload profile picture and it worked but now I get this error accounts/models.py class UserProfile(models.Model): .... … -
Can a child template also use a child template in django?
My child template path is project/sales/templates/sales/table.html. It extends the another child template sale_summary_change_list.html. {% extends 'sale_summary_change_list.html' %} {% block result_list %} <div class="results"> <table> <thead> <tr> {% for header in table %} <th> <div class="text"> <a href="#">{{ header }}</a> </div> </th> {% endfor %} </tr> </thead> <tbody> {% for row in summary %} <tr class="{% cycle 'row1' 'row2'}"> <td> {{ row.color_pref }} </td> <td> {{ row.total | intcomma }} </td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} The parent template is also located in the same folder. (project/sales/templates/sales/sale_summary_change_list.html) {% extends 'admin/change_list.html' %} {% load humanize %} {% block content_title %} <h1> Sales Summary </h1> {% endblock %} {% block result_list %} {% block table %} {% endblock %} {% endblock %} {% block pagination %}{% endblock %} My child template however is not appearing. What am I doing wrong? -
AJAX request duplicates entire page
I am trying to implement chained dependent dropdown combobox selection. I have a 'category' HTML combobox and once the value in there is changed, another combobox should appear to select a subcategory and so on until the innermost (most specific) category is selected. So, whenever the value in the combobox is changed I am firing an AJAX GET request which should reload only that bit of the page, however currently my code just duplicates entire page instead of just creating a new <select>. Here is my Django template with the jQuery code: {% extends 'pages/base.html' %} {% block content %} <h1>Create a product</h1> <form method='POST' id='productForm' data-products-url="{% url 'products:ajax_load_categories' %}"> {{ form.as_p }} </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_category").change(function () { var url = $("#productForm").attr("data-product-url"); var categoryId = $(this).val(); $.ajax({ url: url, data: { 'category': categoryId }, success: function (data) { $("#productForm").append(data); } }); }); </script> {% endblock %} Here is my view: def load_categories(request): category_id = request.GET.get('category') return render(request, 'products/category_dropdown_list_options.html', {'subcategories': subcategories}) Here is my urls.py: app_name = 'products' urlpatterns = [ path('create/', product_create_view, name='product-create'), path('ajax/load-categories/', load_categories, name='ajax_load_categories') ] and here is the tiny bit of HTML I am trying to create: <select> {% for subcategory in subcategories %} <option … -
Is that possible to run django nose test in different project?
Previously I wrote django nose test under app. Is that possible that creating a new project to test other projects? -
Template renders the same information for every user Django
My website has a feature where users can look at each other's profile pages, but at the moment, I have a problem where the currently logged in user's information is being displayed across all the profile pages. This is the code for the views.py view_profile def view_profile(request,pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user args = {'user':user} return render(request,'mainapp/profile.html') And here are the urls.py path('profile/',views.view_profile,name='view_profile'), path('profile/<pk>/',views.view_profile,name='view_profile_with_pk'), And here is the UserProfileInfo model class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50,blank=True,null=True) last_name = models.CharField(max_length=50,blank=True,null=True) description = models.CharField(max_length=150) image = ProcessedImageField(upload_to='profile_pics', processors=[ResizeToFill(150, 150)], default='default.jpg', format='JPEG', options={'quality': 60}) joined_date = models.DateTimeField(blank=True,null=True,default=timezone.now) verified = models.BooleanField( default=False) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) I have tried all sorts of things including switching different things around etc. So for the rest of the code that is relevant to this problem, here is the actual template that is rendering this information {% extends 'mainapp/base.html' %} {% load static %} {% block content %} <p>{{ user }}</p> <p>{{ user.first_name }} {{ user.last_name }}</p><br> <p>{{ user.email }}</p><br> <p>{{ user.userprofileinfo.description }}</p><br> <img class="rounded-circle account-img" src="{{ user.userprofileinfo.image.url }}"> {% endblock %} The result that I wanted was for the user to be able …