Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, Ajax: 'PostListView' object has no attribute 'object_list'
I am trying to build comment section below every post with ListView. It works with button "submit" but when I try to do it with Ajax I get 500 error in console. In logs I noticed that it shows error 'PostListView' object has no attribute 'object_list'. Code below, thanks for help in advance. views.py class PostListView(FormMixin, ListView): model = Post template_name = 'posts/homepage.html' form_class = CommentForm def get_queryset(self): profiles = Follow.objects.filter(follow_by=self.request.user.profile).values_list('follow_to', flat=True) posts = Post.objects.filter(author_id__in=profiles).order_by('-date_of_create') return posts def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): if request.method == 'POST': pk = self.request.POST.get('pk') post = Post.objects.get(pk=pk) new_comment = Comment.objects.create( author = self.request.user.profile, post = post, content = form.cleaned_data['content'] ) return JsonResponse({'comment': model_to_dict(new_comment)}, status=200) else: return self.form_invalid(form) template <div class="comments" id="{{ post.pk }}" style="display: none"> {% include 'posts/comments.html' %} <form action="" method="post" class="commentForm" data-url="{% url 'post_comments' post.pk %}"> {% csrf_token %} <input type="hidden" name="pk" value="{{ post.pk }}"> {{ form.as_p }} <button type="button" class="commentBtn" id="{{ post.pk }}">Comment</button> </form> </div> addComment.js $(document).ready(function () { $('.commentBtn').click(function () { let serializedData = $('.commentForm').serialize(); let btn = $(this); let id = btn.attr('id'); $.ajax({ url: $("commentForm").data('url'), data: serializedData, type: 'post', dataType: 'json', success: function (data) { console.log(data); $(`#${id}.comments`).load('/posts/comments/' + data.post); $('textarea').val(''); } }) }) }) -
Django Rest - how can i return a custom json response when authentication fails?
I created a custom middleware to authenticate every get request to an API endpoint that i created. Here is my code: class TokenMiddleware(AuthenticationMiddleware): def process_request(self, request): if request.user.is_authenticated: return None else: try: token = request.GET[TOKEN_QUERY_PUBLIC] secret = request.GET[TOKEN_QUERY_SECRET] except Exception as e: # A token isn't included in the query params raise ValidationError(detail=str(e)) user = auth.authenticate(request, token=token, secret=secret) if user: auth.login(request, user) else: return HttpResponse('Authentication failed', status=404) Now, instead of raising exceptions or returning an HTTP response, i would like to return a JSON string instead, something like: {'error': 'authentication failed'}. I know how i would do that from a standard view, but in this case i need to do it from a middleware. How can i do it? Thanks in advance! -
Dynamic request of data from API endpoint in DjangoRestFramework
I am making some API calls from an external source but would like to make it dynamic instead of manually putting the reference number in my views in the DRF UI provided. What I want is that in my DRF UI, I should have a field whereby when I enter a reference number, I should get the response from from the API, I am successfully doing this manually but I want to make it dynamic from the DRF UI. I would also like to get a better formatted JSON Response in my DRF UI. An image is below to better explain what I meant Views.py class Paystack(APIView): def get(self, request): url = "https://api.paystack.co/transaction/verify/{{REFERENCE_NO}}" payload = {} files = {} headers = { 'Authorization': 'Bearer SECRET_KEY', 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers, data= payload, files=files) return Response(response) def post(self, request): url = "https://api.paystack.co/transaction/verify/{{REFERENCE_NO}}" payload = {} files = {} headers = { 'Authorization': 'Bearer SECRET_KEY', 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers, data= payload, files=files) return Response(response) urls.py from django.urls import path, include from .views import * from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('paystack', Paystack, basename='paystack') urlpatterns = [ path('paystack/', Paystack.as_view(), name='paystack'), ] Presently, my DRF UI … -
Usertype models in Django
I'm being confused on where table how I insert my usertypes, I'm just a beginner on Django but surely Im been reading documentation in Django but I can't understand this one , The case is when I register new user there's must be choice what usertype should specify with this user either an admin or etc. but the problem is I think there is no relationship table from authuser even I create another table.slight similar to this problem resources link. For now I'm been thinking to create custom usertype field in authuser table,but when migrate it didn't show updated fields and also some user didn't touch or add any field in authuser table sample Im just really confused of where table I can add my usertype that have a relationship to authuser. Is there any know or explain about this, thanks Models class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() usertype_id = usertype = models.OneToOneField(usertypes,on_delete=models.CASCADE,primary_key=True) () //this is what i want to add class Meta: managed = False db_table = 'auth_user' class usertypes(models.Model): usertype … -
Django Extensions Missing from Docker Environment
Django claims Django Extensions is not installed whenever I try to run anything via manage.py: ModuleNotFoundError: No module named 'django_extensions' I have a Django set up with Docker and wanted to start using the Django Extensions module, so I have added the module to my requirements.txt as follows: django-extensions>=3.0.9,<3.1.0 As part of my Dockerfile, I install my dependencies in the requirements.txt: RUN pip install -r /requirements.txt When I build my environment, I can see it install occurring in the console seemingly without any issues: Collecting django-extensions<3.1.0,>=3.0.9 Downloading django_extensions-3.0.9-py3-none-any.whl (221 kB) ... Successfully installed Django-3.1.2 django-extensions-3.0.9 ... I added this module to INSTALLED_APPS as follows: INSTALLED_APPS = [ ... 'django_extensions', ] Once added to installed apps, Django starts throwing the error I mentioned about the missing module above. This is the same way I am installing my other dependencies such as the Django itself, the Django Rest Framework, etc, and it has no problems. Why wouldn't Django be able to find the Django Extensions module? -
Django escape only certain HTML tags
Is it possible to escape all html tags except for the tag somehow? I am sending a user entered string from a view to an html template where I have manually added tags to the string in the view. I would like to allow for that to be shown, but of course omit all html tags entered by the user. -
Inability to Make External API calls
I am getting this error in my terminal while making some External API request call I am following the documentation from here https://paystack.com/docs/api/#dedicated-nuban def create_nuban(request): url = "https://api.paystack.co/dedicated_account" payload = { "customer":481193, "preferred_bank":"providus-bank" } headers = { 'Authorization': 'Bearer SECRET_KEY', 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data= payload) print(response.text.encode('utf8')) Error message on the terminal b'{\n "status": false,\n "message": "Request body could not be parsed. Make sure request body matches specified content-type: \'application/json\'",\n "data": {\n "parser_message": "Unexpected token c in JSON at position 0",\n "body": "customer=481193&preferred_bank=providus-bank"\n }\n}' -
django restframework HyperlinkedRelatedField return Null value on one to many and many to many relationship
hi i'm new to django restframework, and i have model like this: class Tag(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name class Blog(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE,null=True,related_name='post') tags = models.ManyToManyField(Tag,related_name='tag') def __str__(self): return self.title and my view(sorry if it looks terrible): @api_view(['GET']) @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def userDetail(request,pk): users = User.objects.get(pk=pk) serializer_context = { 'request': request, } serializers = UserSerializers(users,context=serializer_context) return Response(serializers.data) @api_view(['POST']) @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def insertPost(request): serializer = BlogSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) @api_view(['GET']) @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def tagDetail(request,pk): tag = Tag.objects.get(pk=pk) serializer_context = { 'request': request, } serializers = TagSerializers(tag,context=serializer_context) return Response(serializers.data) and this is my serializers: class BlogSerializers(serializers.ModelSerializer): author = serializers.HyperlinkedRelatedField( read_only=True, view_name='user-detail' ) tags = serializers.HyperlinkedRelatedField( many = True, read_only=True, view_name='tag-detail' ) class Meta: model = Blog fields = ('id','title','content','author','tags') class UserSerializers(serializers.ModelSerializer): post = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='blog-detail' ) class Meta: model = User fields = ('id','username','email','first_name','last_name','post') class TagSerializers(serializers.ModelSerializer): class Meta: model = Tag fields = ('id','name') my url: path('user/<int:pk>',views.userDetail,name="user-detail"), path('blog/create',views.insertPost,name="blog-new"), path('blog/',views.blogList,name="blog-list"), path('blogs/<int:pk>',views.userBlog,name="blog-detail"), path('tags/<int:pk>',views.tagDetail,name="tag-detail"), my problem is when i created new blog using HyperlinkedRelatedField, the author field value is null as well as the tag field, but when i dont use it, the result return just fine, … -
Variable hero image in django
In a django webapp, I have a page with a hero image. This happens mostly because there's some CSS (in a .css file) that contains a class called .hero-image with a background-image: tag with url("...") value. Now I'd like to have the image controlled by some logic: something in the world leads to a database lookup that decides whether to use image one.png, two.png, etc. The only reasonable way I see to do this is to move the .hero-image CSS block from the CSS file to be inline CSS served each time the page is served. (This at least seems more efficient than making the .css file be served dynamically instead of from static and so changing all the time.) This seems like something that is likely a relatively common need, so it bothers me that I've not found documentation on it. Am I on target or is there a better way to approach this? -
fieldsets not working in Tabular Inline in Django
I want to use fieldsets in my django project Specifically in a Tabular Inline model ( when it's showing inline with the parent model ) and it's not working for some reason. Here is my code: admin.py: class QuantitiesTabularInline(admin.TabularInline): def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): response = super(QuantitiesTabularInline, self).render_change_form( request, context, add, change, form_url, obj) response.context_data['title'] = "edit" if response.context_data['object_id'] else "Sorts" return response extra = 0 fieldsets = ( ('المستودع', { 'fields': ('warehouse',), }), ('الصنف', { 'fields': ('Sort',), }), ('الكمية', { 'fields': ('Quantity',), }), ) model = Quantities formset = RequiredInlineFormSet -
Django forms are not receiving form data using ajax call
I am writing a simple AJAX site using a Django back-end where you can create articles. Each article has an edit button, which can be used to modify that pre-existing article on the page. This button pops up an edit form (the issue at hand) in a Bootstrap Modal. The edit form has only 3 fields: headline, subheading, and a date (for now). Whatever the field inputs are, they are not sent back to Django properly and the is_valid() method returns False every single time. This is what form.errors gives me as output every single time: <ul class="errorlist"><li>headline<ul class="errorlist"> <li>This field is required.</li> </ul> </li> <li>subheading<ul class="errorlist"> <li>This field is required.</li></ul></li> <li>date<ul class="errorlist"><li>This field is required.</li></ul></li></ul> The "This field is required" is likely because the model does not have blank=True, so the form must be sending empty fields. Below is all my code in question, including the form in HTML, the AJAX call, and the Django form. views.py: # Handles editing articles class ArticleEdit(View): def post(self, request, id): editForm = ArticleForm(request.POST) if editForm.is_valid(): print("Debug: Form is valid") # No Logic here yet return JsonResponse({'edited' : 'OK'}, status=200) else: print(editForm.errors) return JsonResponse({'edited' : 'FAIL'}, status=200) forms.py class ArticleForm(ModelForm): class Meta: model … -
how to control the img attributes src in fetching the data from database in Reactjs
I am creating a article related project. And A article can we wrriten by multiple author.In this I want to show image on webpage if it has src and if it has no src then show empty.I fatched the data by using axios <img className="userpic" src={item.author[0].picture} alt="" /> <img className="userpic" src={item.author[1].picture} alt="" /> <img className="userpic" src={item.author[2].picture} alt="" /> currently the above code is working because in author table all id has the picture.But suppose If there is no picture inside the author[2] then I am getting the error on console Uncaught TypeError: Cannot read property 'picture' of undefined How can we solve it? -
python3 manage.py findstatic can't find static file
I am trying to add static file to my project but css doesn't load. I used findstatic but django doesn't see any static directory: In another project django still can find static folder: My settings.py: STATIC_URL = '/static/' My base.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <link href = "{% static 'css/base.css' %}" rel = 'stylesheet'> <title>{% block title %}Educa{% endblock %}</title> </head> <body> <div id = 'header'> <a href = "/" class = 'logo'>EDUCATION</a> <ul class = 'menu'> {% if request.user.is_authenticated %} <li><a href = "{% url 'logout' %}">Logout</a></li> {% else %} <li><a href = "{% url 'login'%}">Login</a></li> {% endif %} </ul> </div id ='content'> {% block content %}{% endblock %} <script src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/ jquery.min.js'></script> <script> $(document).ready(function(){ {% block domready %} {% endblock %} }); </script> </body> </html> Thank you -
How to filter location inside Lat Long Polygon/Geometry in DJango?
I have a list of lat and long that shape a polygon, and I want to retrieve the location or points that it's lat long inside the polygon. Is Django Geo can do that with MySql database? -
Rading the django model field value in the base template
I have a auth_user model, and a posts model. the posts model has fields like: id, author_id and likes. All I need print likes values related to each user in the base template. like: {{ user.posts.likes }} however it does not work, while {{ user.profile.image.url }} (profile is another model which has user_id) works perfectly. I am importing base templates to other templates like {% extends "app/base.html" %} so I don't see any place in backend to pass the likes values -
Use Django view to group every 3 objects into seperate context variables?
I want to break up my project query projects = Project.objects.all() from my views.py file into groups of 3. I apologize if my question was worded poorly. I'm not entirely sure how to ask this in a short, concise way. Any suggestions on how to better word this and I'll update. My view function currently: def project_index(request): projects = Project.objects.all() project_len = len(projects) project_list = zip(*[iter(projects)]*3) context = { 'projects': projects } return render(request, 'project_index.html', context) I was thinking I could use a dictionary somehow, but after starting to work through this I find myself a little lost as to how to implement it. Ideally, I need to get every 3 objects and create a new context variable for those objects. For example lets say there are 9 objects in total: def project_index(request): projects = Project.objects.all() project_len = len(projects) <---gets the total number of objects project_list = zip(*[iter(projects)]*3) <---converts objects into list, groups of 3(not sure if this will work for what I am trying to do, but it was a thought.) context = { 'projects': projects, 'group1': group1, <---each group contains 3 objects(object1, object2, object3) 'group2': group2, <---(object3, object4, object5) 'group3': group3, <---(object6, object7, object8) } return render(request, 'project_index.html', … -
Django, pass a javascript variable into ListView to filter a queryset
I'd like to use an Ajax variable within a Django Class based ListView. Getting the variable into the view is no problem using request.GET.get however, it seems by doing so, I am put into a dilemma. If I am using def get(self, request) I then have problem using get_queryset and get_context If I skip using def get(self, request) I have problem getting the Ajax variable into the view. I'd like to ask for some help to get it working. The ultimate aim is to produce a filtered context that will be used to produce an email. class ProductListSendView(LoginRequiredMixin, ListView): model = Product template = 'product/product_email.html' def get(self, request): _req_list = json.loads(request.GET.get('ids', None)) _res = [int(i) for i in _req_list] return _res def get_queryset(self, _res): queryset = super(ProductListSendView, self).get_queryset() qs = queryset.filter(id__in=_res) return qs def get_context_data(self): context = super(ProductListSendView, self).get_context_data() context['page_title'] = 'Authors' self.send_email(context) return context the js function (for completeness) var getProducts = function () { var table = $('#product_list-table').DataTable(); var ids = $.map(table.rows('.selected').data(), function (item) { return item[1]}); jQuery.ajax({ type: 'GET', url: "/product/list/send/", data: { ids: JSON.stringify(ids), }, success: function(data) {}, error: function(xhr, textStatus, error) { console.log(error); } }); }; -
Windows + mod_wsgi + Apache 2.4 + Django - mod_wsgi error: ModuleNotFoundError: No module named 'django'\r
I am trying to deploy my first basic Django Application for study purposes. I have not much experience and after few days i decided to find help here. I want to use Apache 2.4 + mod_WSGI + Django at Windows server. I was following instructions from youtube's video: https://www.youtube.com/watch?v=frEjX1DNSpc After all steps done i cannot access duo to error: ModuleNotFoundError: No module named 'django'\r I do not use VEnv Apache seems to work fine Django is in instaled pip list and seems obtainable C:\Apache24\logs\error.txt The 'Apache2.4' service is running. pm_winnt:notice] [pid 12736:tid 596] AH00455: Apache/2.4.46 (Win64) mod_wsgi/4.7.1 Python/3.7 configured -- resuming normal operations [Sun Oct 25 10:08:29.519101 2020] [mpm_winnt:notice] [pid 12736:tid 596] AH00456: Apache Lounge VS16 Server built: Oct 2 2020 11:45:39 [Sun Oct 25 10:08:29.519101 2020] [core:notice] [pid 12736:tid 596] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Sun Oct 25 10:08:29.521101 2020] [mpm_winnt:notice] [pid 12736:tid 596] AH00418: Parent: Created child process 13836 [Sun Oct 25 10:08:29.851909 2020] [mpm_winnt:notice] [pid 13836:tid 624] AH00354: Child: Starting 64 worker threads. [Sun Oct 25 10:08:35.795055 2020] [wsgi:error] [pid 13836:tid 1148] [client ::1:61451] mod_wsgi (pid=13836): Failed to exec Python script file 'C:/Users/Mateusz/Documents/GitHub/Production-tool/Zeus/Zeus/wsgi.py'. [Sun Oct 25 10:08:35.795055 2020] [wsgi:error] [pid 13836:tid 1148] [client ::1:61451] mod_wsgi (pid=13836): … -
Django CARDINALITY Query does not allow filtering by equals but does work for < or >
I have a Document model, which contains an ArrayField of pages. I want to find a list of all documents that have zero pages. Model field: content = ArrayField(models.TextField(), default=list, blank=True) I use an annotation function to first create a calculated field for number of pages, and then try to filter on pages equal zero. Here is the query I'm trying to run: qs = Document.objects.all() \ .annotate(content_len=Func(F('content'), function='CARDINALITY')) \ .exclude(content_len=0) # this DOESN'T WORK .exclude(content_len__lt=1) # this WORKS The version that doesn't work generates the following SQL error: WHERE CARDINALITY("dockets_document"."content") = 0::text[] >>> psycopg2.errors.CannotCoerce: cannot cast type integer to text[] -
extra_context variables are not passed to changelist template
Trying to modify standard admin list template, for this I'm passing extra_context: def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} extra_context['stats'] = 'test' resp_view=super().changelist_view(request, extra_context=extra_context) return resp_view And using this in the template: ... <div class="results"> <p> Statistics: {{ stats }} </p> <table id="result_list"> ... But it doesn't pass it for some reason. Although when I look into the fields of resp_view, it's in the context data: (Pdb) p resp_view.context_data {'site_title': 'Django site admin', ..., 'stats': 'test'} What can be the problem here? I understand it's official way of passing extra variables into the template? -
Passing a variable to the form action
So I have first form in which user chooses profile: class ProfileChoice(forms.ModelForm): def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id',None) super(ProfileChoice, self).__init__(*args, **kwargs) self.fields['login'].queryset = Profile.objects.all().filter(created_by_id = self.user_id) login = forms.ModelChoiceField(queryset= None, label='Profile') class Meta: model = Profile fields = ('login',) On submit I need to redirect him to the next form which is this: class TranslatorChoice(forms.ModelForm): def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id',None) super(TranslatorChoice, self).__init__(*args, **kwargs) self.fields['owner'].queryset = Translator.objects.all().filter(owner_id = self.user_id) owner = forms.ModelChoiceField(queryset = None) class Meta: model = Translator fields = ('owner',) with this view: class ProfileOwner(UpdateView): model = Profile template_name = 'registration/update.html' success_url="/account/" form_class = TranslatorChoice @method_decorator(user_passes_test(client_check, login_url='/account/')) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_form_kwargs(self): kwargs = super(ProfileOwner, self).get_form_kwargs() kwargs['user_id'] = self.request.user.id return kwargs def get_object(self, queryset=None): profile = super(ProfileOwner, self).get_object(queryset) if profile.created_by != self.request.user: raise Http404("Profile doesn't exist") return profile The update needs to be performed on the profile which was chosen in the first form. I am trying to do it with passing a pk to the URL. Here's urls.py: url(r'^update/(?P<pk>\d+)', ProfileOwner.as_view(), name='profile_owner_update') and my template is here: {% extends 'base.html' %} {% block content %} <h2>Add profile</h2> <form method="post" action="{% url 'profile_owner_update' pk=id %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Choose</button> … -
Cannot resolve keyword 'slug_iexact' into field. Choices are: Tag_Name, id, posts, slug
I am getting the following error: FieldError at /tag/htc_phones/ Cannot resolve keyword 'slug_iexact' into field. Choices are: Tag_Name, id, posts, slug models.py : class Tag(models.Model): Tag_Name = models.CharField(max_length=100) slug = models.SlugField(unique=True,editable=True,max_length=200) def __str__(self): return self.Tag_Name def get_absolute_url(self): return reverse('tag_detail_url', kwargs={'slug':self.slug}) views.py: def tag_detail(request,slug): tag = Tag.objects.get(slug_iexact=slug) return render(request,'website_primary_html_pages/tag_detail.html',context={'tag':tag}) how to fix this problem , thanks -
Reorder siblings with Django-mptt
I have a tree structure as follows: Financial Statements Balance Sheet Non-Current Assets Property, Plant & Equipment Buildings Plant & Machinery Long Term Investments..... The relevant model is as follows: class Category(MPTTModel): name = models.CharField(max_length=255) ordering = models.IntegerField() parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPPTMeta: order_insertion_by = ['ordering'] I need to allow users to be able to reorder siblings from the front-end using the field "ordering". I set the "ordering" of: Long Term Investments to 0 Property, Plant & Equipment to 1 then I ran the following code in views.py: def category(request): Category.objects.rebuild() tree_obj = Category.objects.all() structure = get_structure(tree_obj) print(structure) The result is: <TreeQuerySet [<Category: Financial Statements>, <Category: Balance Sheet>, <Category: Non-Current Assets>, <Category: Property, Plant & Equipment>, <Category: Buildings>, <Category: Plant & Machinery>, <Category: Long Term Investments>... I expected "Long Term Investments" to appear before "Property, Plant & Equipment" and its children. What am I doing wrong? -
Django 3 template date tag return nothing
I'm try to use date template tag to format datetime from database 2020-10-23 08:59:44.792274 on django template {{ item.payment_received_time }} # return 2020-10-23 08:59:44.792274 {{ item.payment_received_time|date:"D d M Y" }} # return nothing but nothing is returned, what am I missing on it ? Thanks -
Django Save Image Path to Database
I'm new to Django and I want to save the image path to the Postgres database. I'm asked to use Charfield in my model not Imagefield. How can I do that? Thanks in advance.