Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverse match looking in the wrong place?
I am trying to link to an app in my website from the base template using the django template tags - but it keeps looking in the wrong app and I don't know why. Here is the code for my base html file: <!DOCTYPE html> <html> <head> <title>kinbank</title> {% block head %}{% endblock %} </head> <body> <div> <div class="page-width"> <h1 class="top-org-name"> </h1> <div class="nav"> <a href="{% url 'home:index' %}">Home</a> <a href="{% url 'languages:index' %}">Languages</a> </div> <div class="clear"> </div> </div> </div> {% block content %}{% endblock %} </body> and the base urls file urlpatterns = [ path('languages/', include('languages.urls')), path('home/', include('home.urls')), path('admin/', admin.site.urls), ] The strange thing is that the home link works but the languages link does not. The error I get is: TemplateSyntaxError at /home/ But the error occurs in this line <a href="{% url 'languages:index' %}">Languages</a> Here is the traceback: Traceback: File "/Users/sp16194/.local/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/sp16194/.local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/Users/sp16194/.local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sp16194/Desktop/Projects_Git/kinbank3/kinbank/home/views.py" in index 18. return HttpResponse(template.render(context, request)) File "/Users/sp16194/.local/lib/python3.5/site-packages/django/template/backends/django.py" in render 61. return self.template.render(context) File "/Users/sp16194/.local/lib/python3.5/site-packages/django/template/base.py" in render 171. return self._render(context) File "/Users/sp16194/.local/lib/python3.5/site-packages/django/template/base.py" in _render 163. return self.nodelist.render(context) File "/Users/sp16194/.local/lib/python3.5/site-packages/django/template/base.py" … -
Create new django project in pycharm: "Remote path not provided"
After creating a python docker container, I want to use it as my interpreter instead of Virtualenv. If I leave it empty it says "Remote path not provided". After typing something you see the warning on the screenshot. Screenshot: How can I fix it? -
Why accessing page_range is different in shell and template?
I am totally new in Django and currently learning pagination. This question confused me and I need your help to help me understand it. In order to access page_range value in shell, I directly type in pages.page_range as code below: >>> from django.core.paginator import Paginator >>> posts = [1, 2, 3, 4, 5, 6, 7] >>> pages = Paginator(posts, 2) >>> pages.page_range # here range(1, 5) but in template in order to access page_range value we need to type in page_obj.paginator.page_range. The question is why it is throwing an error if I access page_range without .paginator mediation like page_obj.page_range, since in shell we don't need to type pages.paginator.page_range? Please help me understand what I am missing here. Thank you -
How do I retrieve column content?
I am trying to get content of a field with queryset command 'Post.objects.values('country__name')' and I am getting following error. NoReverseMatch at / Reverse for 'cities' with arguments '('',)' not found. 1 pattern(s) tried: ['accounts\\/cabinet\\/cities\\/(?P<pk>[0-9]+)\\/$'] Although I don't get any error when I type this command in django shell. my view: def home(request): user = User.objects.all() cname = request.POST.get('dropdown1') city = Post.objects.all().distinct('city') country = Post.objects.values('country__name') print(country) context = { 'country': country, 'user': user, 'city': city } return render(request, 'registration/home.html', context) my model: class Post(models.Model): title = models.CharField(max_length=255) country = models.ForeignKey(Country, on_delete=models.CASCADE) city = models.CharField(max_length=255) address = models.CharField(max_length=255) email = models.EmailField(max_length=255) phone = models.CharField(max_length=255) website = models.URLField(max_length=255, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.city def get_absolute_url(self): return reverse('users:blog') my urls.py urlpatterns = [ path('accounts/register/', UserRegistrationView.as_view(), name='register'), path('accounts/cabinet/', views.profile, name='cabinet'), path('accounts/cabinet/blog/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('accounts/cabinet/new/', PostCreateView.as_view(), name='post-create'), path('accounts/cabinet/blog/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('accounts/cabinet/blog/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('', views.home, name='home'), path('accounts/cabinet/blog/', views.blog, name='blog'), path('accounts/cabinet/countries/', views.countries, name='countries'), path('accounts/cabinet/cities/<int:pk>/', views.cities, name='cities'), path('accounts/cabinet/address/<int:pk>/', views.address, name='address'), ] -
Formset with extendable rows quantity without JS( 2 models + files in both)
Hello Stackoverflow community. I need to add formset lines in template when user would click button on the form’s page. Formset contains multiple Imagefields for saving images and It’s inlineformset. secondary_inline_formset = inlineformset_factory(MainModel, SecondaryModel, fields=("boat_photo", ), extra=1, can_delete=True, ) Problem is when page gets reloaded, data from the form 1 would be still present, but files from the formset (form2) would be gone. Adding new lines to the formset in forms works great, both models save with proper mutual relationship , but files don't stay more then 1 iteration( when i click "add new line" files would be gone, but text data are still here) code: @atomic @login_required def viewname(request): # saving firstly primary model here if request.method == 'POST': form1 = MainForm(request.POST, request.FILES, prefix="form1") if form1.is_valid(): prim = form1.save(commit=False) prim.author = request.user form1.save(commit=False) form2 = secondary_inline_formset(request.POST, request.FILES, prefix="form2", instance=prim) # connecting formset with the instance here # idea is to tweak ['form2-TOTAL_FORMS'] parameter by increasing it to 1 each time so that when #form gets #reloaded we will have 2 form_set areas , then 3, etc, etc , etc, each time user would clicks "add" button # "add_photo" comes from the template with the POST request and indicates that … -
Django Rest Framework - Using Session and Token Auth
I am trying to get this working without success, and don't know if this is possible, and if should be doing it like this. I developed a web app using Django + Rest-Framework + jQuery, and I want to have an external application to consume the same REST API, using JWT Tokens for authentication. My current config is like this. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_RENDERER_CLASS': [ 'rest_framework.renderers.JSONRenderer', ] } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('Bearer',), } views.py class ListFileView(APIView): permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): user = request.user if user: obj = Foo.objects.filter(owner=user) serializer = FooSerializer(obj, many=True) data = serializer.data return Response(data, status=status.HTTP_200_OK) return Response({'detail': 'You have no access to files.'}, status=status.HTTP_400_BAD_REQUEST) The tricky parte is that when i use: permission_classes = (IsAuthenticated,) I can perform ajax calls from an external application (using a valid JWT token), but jQuery calls from within the app (with an authenticated user) fail with: {"detail":"Authentication credentials were not provided."} And on the other hand, if I use autentication_classes instead of permission_classes: authentication_classes = (SessionAuthentication, BasicAuthentication) I can perform ajax calls from within the web app using jQuery, but external calls fail with the same 403 error. I tried … -
Using react-router with Wagtail Api
I am trying to build a web site (xyz.com as an example ) that uses react and react-router on the frontend. I am using Wagtail API and Django on backend. Wagtail API and wagtail has its own url-path structure: re_path(r'^api/v2/', api_router.urls), re_path(r'^admin/', include(wagtailadmin_urls)), re_path(r'^documents/', include(wagtaildocs_urls)), re_path(r'', include(wagtail_urls)), I want react-router to handle all the urls including root (xyz.com/) except xyz.com/api/v2, xyz.com/admin, xyz.com/media. Is there a proper way of doing this in Django urls.py? -
How to fix query django
I want the output to be in the order of time and a total of 8. What should I do? This code only works in the order of the objects in the list, and this is not my request Excuse me, my first language is not English from itertools import chain from app_adventure.models import * from app_children.models import * from app_cultural.models import * my_popular_h = [AdventureTor.objects.order_by('-list_date'), CulturalTor.objects.order_by('-list_date'), ChildTor.objects.order_by('-list_date') ] my_popular_h = [query.filter(popular_h=True) for query in my_popular_h] popular_list = list(chain(*my_popular_h)) >>> popular_list >>> [<AdventureTor: valley>, <AdventureTor: sky>, <AdventureTor: scroling>, <AdventureTor: rock>, <AdventureTor: mounthin>, <AdventureTor: jungel>, <AdventureTor: desert>, <AdventureTor: bike>, <CulturalTor: Culturalhistori>, <CulturalTor: Cultural mousiam>, <CulturalTor: Cultural city>, <ChildTor: child his>, <ChildTor:child natural>, <ChildTor:child Cultural>] -
django-filter checkbox submit
I am using django-filter==2.1.0 for implementing search filter. I already implement it. But now i need to search by clicking checkbox not by search button. My codes are given below: models.py class Book(models.Model): name = models.CharField(max_length=100) publication = models.ForeignKey(Publication, on_delete=models.CASCADE) filters.py class BookFilter(django_filters.FilterSet): publication = django_filters.ModelMultipleChoiceFilter(queryset=Publication.objects.all(), widget= forms.CheckboxSelectMultiple) class Meta: model = Book fields = ['publication'] views.py def test_view(request): book_list = Book.objects.all() book_filter = BookFilter(request.GET, queryset=book_list) temp = book_filter.form return render(request, 'test.html', {'filter': book_filter}) template {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} <form method="get"> {% for choice in filter.form.publication %} <label> {{ choice.tag }} <span class="max-content-width">{{ choice.choice_label }}</span> </label> {% endfor %} <button type="submit">Search</button> </form> <ul> {% for book in filter.qs %} <li>{{ book.name }}</li> {% endfor %} </ul> {% endblock %} It's working properly. But i want to add widget = forms.CheckboxInput(attrs={'onclick': 'this.form.submit();'}) in my filters.py for checkbox input. I don't understand how can i add another widget. Please help me to solve this problem. -
Django DRF add request.user to modelserializer
I am using django rest framework, and I have an object being created via a modelviewset, and a modelserializer. This view is only accessible by authenticated users, and the object should set its 'uploaded_by' field, to be that user. I've read the docs, and come to the conclusion that this should work viewset: class FooViewset(viewsets.ModelViewSet): permission_classes = [permissions.IsAdminUser] queryset = Foo.objects.all() serializer_class = FooSerializer def get_serializer_context(self): return {"request": self.request} serializer: class FooSerializer(serializers.ModelSerializer): uploaded_by = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) class Meta: model = Foo fields = "__all__" However, this results in the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: bar_foo.uploaded_by_id Which suggests that "uploaded_by" is not being filled by the serializer. Based on my understanding of the docs, this should have added the field to the validated data from the serializer, as part of the create method. Clearly I've misunderstood something! -
Dynamic URL not working. NoReverseMatch at /cpp/1/view/
Error is django.urls.exceptions.NoReverseMatch: Reverse for 'answer' with arguments '('', 1)' not found. 1 pattern(s) tried: ['(?P<subforum_name>[-a-zA-Z0-9_]+)\\/(?P<ques_id>[0-9]+)\\/answer\\/$'] template: <a href="{% url 'jmiforums:answer' subforum.subforum_name ques_id %}">Give Answer</a> url.py: path("<slug:subforum_name>/<int:ques_id>/view/", views.view_question, name="view_question"), path("<slug:subforum_name>/<int:ques_id>/answer/", views.answer, name='answer'), views.py: @login_required def view_question(request, subforum_name, ques_id): ques = Question.objects.get(pk=ques_id) ques_text = ques.ques_text ans = Answer.objects.filter(ques_id=ques_id).values() context = { 'ques_text': ques_text, 'ques_id': ques.id, 'ans': ans, } return render(request, 'jmiforums/view_question.html', context) I think i have passed correct arguments in url in my template but it is not working. Apparently wants a argument for /answer/ which dosnt makes sense for me. Thanks in advance -
How to set different permission_classes for GET and POST requests using the same URL?
I am building endpoints using DRF (Django Rest Framework). django==2.1.5 djangorestframework==3.9.1 django-rest-auth djangorestframework-jwt I have model "Item" and I want to set different permission_classes for GET and POST requests. Here is how i do it: @csrf_exempt @api_view(['GET', 'POST']) @authentication_classes([TokenAuthentication]) @permission_classes([AllowAny]) def item_list(request): if request.method == 'GET': items = Item.objects.all() serializer = ItemSerializer(items, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = ItemSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) I want to use one endpoint for all methods, like this: urlpatterns = [ path('api/item/', views.item_list), path('api/item/<int:pk>/', views.item_details), ] I want to AllowAny user for GET request method and check if isAdminUser for POST request method Can i do it like in Flask, i.e. one decorator for one method? -
Can't connect to MySQL server on 'localhost
(2002, "Can't connect to MySQL server on 'localhost' (10061)") django in python -
Make cyclically dependent model properties queriable in graphene-django
Say I have Django models looking as follows: class User(Model): username = CharField(...) @property def projects(self): return # projects the user is assigned to class Project(Model): name = CharField(...) @property def users(self): return # users assigned to the project class Assignment(Model): user = ForeignKey(User) project = ForeignKey(Project) (I intentionally did not write the querysets for the properties to make the code more readable.) I would like to be able to see those properties in graphene-django queries. My ModelType classes look like this: class UserType(DjangoObjectType): class Meta: model = User projects = List(ProjectType) class ProjectType(DjangoObjectType): class Meta: model = Project users = List(UserType) However, this code does not work, since ProjectType in the UserType class is undefined, and swapping those classes won't help much. I tried to not include the properties at all and after all the ModelType classes are created, I tried to add the properties via setattr(). Such hack for sure sets the attributes so the classes have the exact same structure, but it seems to be too late: the properties are not accessible from GraphQL at all. Now I ran out of ideas. Is there any way to achieve the desired behavior? -
How to make images to responsive by cloudinary Django SDK?
I am developing my django project. I would like to make some images responsive by cloudinary django SDK. -This works but not responsive ```index.html {% load cloudinary %} {% cloudinary post.image.url width=200 %} ``` -for responsive, I tried this but dosen't work. ```base.html & index.html <head> ~~~ <script src="cloudinary-core-shrinkwrap.js" type="text/javascript"> </script> </head> <body> {% load cloudinary %} {% cloudinary post.image.url crop="fill" width="auto" %} ~~~ <script type="text/javascript"> var cl = cloudinary.Cloudinary.new({cloud_name: "xxxx"}); cl.responsive(); </script> </body> VERSIONS: Django Version: 2.1.4 Python Version: 3.7.2 local host MY code again... ```settings.py INSTALLED_APPS = [ ... 'cloudinary', 'cloudinary_storage', ] ``` ```base.html <head> <!--cloudinary --> <script src="cloudinary-core-shrinkwrap.js" type="text/javascript"> </script> </head> <body> {% block content %} {% endblock %} ~~~ <!--cloudinary --> <script type="text/javascript"> var cl = cloudinary.Cloudinary.new({cloud_name: "hmtmgjlio"}); cl.responsive(); </script> </body> ``` ```index.html {% extends 'base.html' %} {% load cloudinary %} {% cloudinary post.image.url crop="fill" width="auto" %} ``` I expect the img tag by django SDK like this. official django SDK https://cloudinary.com/documentation/django_image_manipulation -
Does django have a user editable templating language that is secure like liquid?
Does django have a user editable templating language that is secure like rails has liquid? i.e. an end user can't hack template code to somehow access properties of sensitive template variables -
Djangos truncatewords in twig
Django has a filter called truncatewords, and truncatewords_html, that Truncates a string after a certain number of words. Is there a similar function / what is the best way to achieve the same thing in twig (symfony in the backend). Twigs slice function is not what I'm looking for since it doesn't respect spaces / words. -
Django - Database is empty after running migrations
When I try to migrate my models to the default sql database in django, using pycharm, the db is empty after running migrations. This problem occurs with all my projects. My app is called demoapp. I have ran the following commands in the pycharm terminal, with these results: python manage.py makemigrations Migrations for 'demoapp': demoapp\migrations\0001_initial.py - Create model Question - Create model User python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, demoapp, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying demoapp.0001_initial... OK Applying sessions.0001_initial... OK Yet, after these two commands, the db database in the database window in pycharm is empty and underlined red, while it should actually show the correct schema. -
How to overwrite a content of DetailView before rendering
I am developing a wiki. An author writes something like [Food|Bread] in the content field of Article model. Then, I want to overwrite [Food|Bread] with <a href="/path/to/Bread/detail/page/">Bread</a> if Food.objects.filter(name="Bread").exists() is true, before rendering. How to overwrite article.content temporarily before rendering? -
Is it a good practice to store basket or shopping items in session? (Django)
I'm writing an e-commerce system using Django, now I need to create a shopping basket mechanism. I use Django session for adding, removing and updating shopping cart but I don't know is it a good practice? or are there any better solution? -
How can I get the nested object of a user from UserProfileModel?
UserProfileModel matching query does not exist. This is what I get when I filter my model in order to get the user object from the UserProfileModel so I can use it as the current logged user. And also, so I can be able to update the other nested related filed with the user. def get_object(self): return UserProfileModel.objects.get(user_id=self.request.user) **# UserProfileModel matching query does not exist.** class UserProfileModel(models.Model): # The User model. user = models.OneToOneField(User, on_delete=models.CASCADE, default='') # The additional nested fields are here # Address fileds: 'address_1', 'address_2' ... address = models.OneToOneField( AddressModel, on_delete=models.CASCADE, related_name='user_address', default='', ) -
HyperlinkedRelatedField DRF does not work with a ViewSet
I have these models: class ExamSheet (models.Model): pass class Exam(models.Model): exam_sheet = models.ForeignKey('myapp.ExamSheet', related_name='exams', ) Serializer: class ExamBaseSerializer(serializers.ModelSerializer): exam_sheet = serializers.HyperlinkedRelatedField(queryset=ExamSheet.objects.all(), view_name='examsheet-detail') class Meta: model = Exam fields = ('id', 'user', 'exam_sheet', ) read_only_fields = ('id', 'user',) But this throws me an error: ImproperlyConfigured at /api/exams/ Could not resolve URL for hyperlinked relationship using view name "examsheet-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. How can I use HyperlinkedRelatedField to show a link to a related model in my serializer? -
how to pass context variable from a template to a view in django
I have one html page which shows me the list of all passengers reading it from db looks something like below and the code snippet below the image: Forms.py <form action="{% url 'test' %}" method="POST"> {% for record in obj %} <div class="container"> {% csrf_token %} <div class="card"> <div class="card-body"> <div class="row"> <div class="col">{{ record.id }}</div> <div class="col">{{ record.detination }}</div> <div class="col">{{ record.arrivaltime }}</div> <div class="col">{{ record.gender }}</div> <div class="col">{{ record.luggage }}</div> <div class="col">{{ record.flag }}</div> <div class="col">{{ record.phonenum }}</div> <button id="button1">Request</button> </div> </div> </div> </div> {% endfor %} </form> As you can see each entry has a request button associated to it,so on each single click i want that particular entry to get stored in Db. I have a view which take the request from the template and should store those 7 parameters values which are inside div tags in db. Views.py def test(request): form = BlogCommentsForm(request.POST) if form.is_valid(): form.save() The problem is when i get the request in the view there are two problems i can see: My form returns is_valid() as Flase. all the object list getting passed rather than a single entry. The results of request.POST were supposed to bejust for a single click of entry, … -
Is it possible, the data gets copied automatically when selecting some data in a searchable pdf?
I am working on a project in which I need to write a code which can help in copying the data automatically when selecting from a searchable pdf which is being shown on the website. I am using Django for development. -
How to install scheduled in Django?
I am working on a web app using Django,How to run scheduler peroidically Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this. How to install or configure it? To clarify: I know I can set up a cron job to do this, but I'm curious if there is some feature in Django that provides this functionality. I'd like people to be able to deploy this app themselves without having to do much config (preferably zero). I've considered triggering these actions "retroactively" by simply checking if a job should have been run since the last time a request was sent to the site, but I'm hoping for something a bit cleaner.