Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use multiple beforeshowday functions django?
I wish to give specific color to specific dates in datepicker and also disable the weekend days. Please help me out. Thank You! <script type="text/javascript"> $(document).ready(function() { var LiveDates = {}; LiveDates[new Date('07/18/2019')] = new Date('07/18/2019'); $('.datepicker1').datepicker({ dateFormat: 'yy-mm-dd', minDate: new Date({{a}},{{b}},{{c}}), maxDate: new Date({{d}},{{e}},{{f}}), beforeShowDay: function(date) { var Highlight = LiveDates[date]; if (Highlight) { return [true, "live", 'Tooltip text']; } else { return [true, '', '']; } } }); }); </script> -
How to store user review to database separately
I am trying to store user review to separate database table. e.g have two images(e.g image1 and image2), if user comments to image1 I want to store user comments to image1 Table. If someone commenting to image2 data stored to image2 Table. How to do this Please help me. view.py def review(request): address = request.session['address'] image1 = Offers.objects.filter(address=address) image2 = Ads.objects.filter(address=address) if 'username' in request.session: if request.method == 'POST': form = Comments(request.POST) if form.is_valid(): review = request.POST.get('review') id = request.POST.get('id_off') dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S') result1 = Image1(review=review, id= id, date_time= dt) result2 = Image2(review=review, id= id, date_time= dt) result1.save() result2.save() return render(request, 'index.html', {'image1': image1, 'image2': image2}) return redirect('/review/') return redirect('/review/') return redirect('/review/') index.html {% for item in image1 %} <div class="col-md-4"> <div class="divi" style="height: 910px"> <img src="{{ item.image.url }}" alt="Images" width="300px" height="200px"/> <p>From Date: {{ item.from_date }}</p> <p>TO Date: {{ item.to_date }}</p> <p>Description: {{ item.description }}</p> <p>Address: {{ item.address }}</p> <!--if this ids ad: <form method="post" action="#"> elif:--> <form method="post" action="#"> {% csrf_token %} <input type="text" name="id_off" value="{{ item.id }}" style="display: none"> <input type="text" name="review"> <button type="submit">Send Review</button> </form> </div> </div> {% endfor %} </br> {% for items in image2 %} <div class="col-md-4"> <div class="divi" style="height: 410px"> <img src="{{ … -
Instance is not ListSerializer when many is True
The serializer is instantiated with many=True but isinstance(self, ObjectListSerializer) is False so the id field isn't being added back to the validated data in to_internal_value() class ObjectSerializer(serializers.ModelSerializer): class Meta: model = Object fields = ( 'id', 'other_field' ) read_only_fields = ('id',) list_serializer_class = ObjectListSerializer def to_internal_value(self, data): ret = super().to_internal_value(data) if all((isinstance(self, ObjectListSerializer), self.context['request'].method in ('PUT', 'PATCH'))): ret['id'] = self.fields['id'].get_value(data) return ret type(self) is still ObjectSerializer I know that it's many=True because the payload is a list and in the view get_serializer() is overidden. def get_serializer(self, *args, **kwargs): data = kwargs.get('data', None) if isinstance(data, list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) Django==2.2.1 and djangorestframework==3.9.4 -
Portable python package with Django inside?
So, I'm trying to figure out, how to create fully portable python package having my venv included with django and several other related packages. I know this question is not new, but all tools are exists for freezing python apps on windows are not doing what i need. p2exe, pyInstaller, etc, are good but can't handle django framework. I want my app has one exe, which will start 1) python intpreter from subfolder 2) my venv with django and other deps 3) manage.py runserver with params Currently 2 and 3 works, if user installed python before runing my starter script (i'm actually wrapping all this with electron, so my web-app will be usable separately from browser) The main question is how to adjust python to work wih provided venv, without having it installed on target machine? -
Django approved comments
first of all, my problem is that I take comments with statusc = 2 and I don't have any problems. But with this code "{% for reply in comment.replies.all%}" appears with all approved or unanswered replies views.py comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date')..... Model.py class Comment(models.Model): STATUS_C_DRAFT = 1 STATUS_C_PUBLISHED = 2 STATUSES_C = ( (STATUS_C_DRAFT, 'Draft'), (STATUS_C_PUBLISHED, 'Published'), ) post=models.ForeignKey(Post,verbose_name='post',related_name='comment',on_delete=models.CASCADE) name=models.CharField(verbose_name="name",max_length=60,blank=False) email=models.EmailField(max_length=120,blank=False,verbose_name="email") comment=models.TextField(max_length=1000,verbose_name="comment") reply=models.ForeignKey('Comment',null=True,related_name='replies',on_delete=models.CASCADE) date=models.DateTimeField(auto_now_add=True) statusc = models.SmallIntegerField(choices=STATUSES_C,default=STATUS_C_DRAFT) Html page {% for comment in comments %} <!-- POST COMMENT --> <div class="post-comment"> <!-- POST COMMENT USERNAME --> <p class="post-comment-username">{{ comment.name }}</p> <!-- /POST COMMENT USERNAME -->.... {% for reply in comment.replies.all %} <div class="post-comment"> <!-- POST COMMENT USERNAME --> <p class="post-comment-username">{{ reply.name }}</p> <!-- /POST COMMENT USERNAME -->... {% endfor%} {%endfor%} -
Update nested serializer with an overwritten to_representation
Context So i have an AlbumSerializer with a nested TrackSerializer. For convenience on the frontend I overwrite the representation of AlbumSerializer to make a dictionary of the tracks instead of a list. class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('id', 'order', 'title') # directly upsert tracks def create(self, validated_data): obj, created = Track.objects.update_or_create( album_id= validated_data['album_id'], order=validated_data['order'], defaults={'title': validated_data['title']} ) return obj class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') # make a dictionary of the tracks def to_representation(self, instance): representation = super().to_representation(instance) representation['tracks'] = {track['id']: track for track in representation['tracks']} return representation #update tracks with the album endpoint def update(self, instance, validated_data): for track in validated_data['tracks'] obj, created = Track.objects.update_or_create( album_id= track['album_id'], order=track['order'], defaults={'title': track['title']} ) return obj Problem Now when i try to update the album, including some track titles, i receive Expected a list of items but got type \"dict\". Which makes sense. Question How can i make DRF accept dictionaries instead of a list if tracks ? -
Basic group hierarchy in python django
I'm building a student registration system by using django where students are registered. Students can be viewed only by their class teachers and school principals based on object level permission. There are School, Class and Student models. Each school can have more than one school principals and each class can have more than one class teachers. There will be two object level permissions: School principals will be able to see all of the students registered to their school. They won't be able to see students of other schools. Class teachers will be able to see the students that are registered to their classes. They won't be able to see students registered to other classes in the same or different schools. I have searched through various 3rd party django libraries to implement such a hierarchical user group architecture. I have seen django-groups-manager, but it is a bit complicated for my issue. Then, I decided on django-mptt's registration of existing models feature and come up with model implementations such as: from django.contrib.auth.models import Group from django.db import models import mptt from mptt.fields import TreeForeignKey TreeForeignKey(Group, on_delete=models.CASCADE, blank=True, null=True).contribute_to_class(Group, 'parent') mptt.register(Group, order_insertion_by=['name']) class School(models.Model): """School object""" name = models.CharField(max_length=255) group = models.ForeignKey( Group, … -
how to develop a Task Management App using django
i am about to work on a project to develop a task management web app which should be able to create projects, create tasks in a particular project, assign team members to a particular task, track each team members' work flow and records and should be a able to display all activities of the project on a dashboard. will also want to integrate a live chat for team members to discuss. all this is to be done using django frameworks. i will need help on how to go about this development process. thank you. -
Wagtail RichTextField not showing in Django ModelForm
My problem is that the RichTextField is the only field not displayed in the form. I have a Model: class RealestateObject(models.Model): title = models.CharField( max_length=256, verbose_name=_('Object Title'), ) summary = RichTextField( verbose_name=_('Summary'), blank=True, null=True, ) description = models.TextField( verbose_name=_('Description'), blank=True, null=True, ) And a form: class RealestateObjectForm(forms.ModelForm): class Meta: model = TestRealestateObject fields = ('title', 'summary', 'description' ) and my template: <form method="POST" action=""> {% csrf_token %} {{ form }} <button type="submit">Insert</button> </form> the title and description field are displayed in the form, the summary not. Is there a solution for this and/or a work around? I can't use the Wagtail Form Builder. It also would be great if I could use the richtext editor. thanks. -
"How to write it in django"
I want to write a code in django template like this: for i in range(6): if i%2==0: print i, i+1 <table class="pp-choice-careers"> <caption>Parent's Choice for Interest Careers</caption> <tr><th>Careers</th><th>Why this career</th></tr> {% for career in resultArr.parent_choice_career %} <tr class="pp-class"> {% if forloop.counter|mod:2 == 0 %} <td>{% if career == 'NA' %}Not Available{% else %} . {{career.answer}}{% endif %}</td> {% else %} <td>{% if career == 'NA' %}Not Available{% else %}{{career.answer}}{% endif %}</td> {% endif %} </tr> {% endfor %} </table> I want to print two values from a list in a row in two columns, so I need current+1 index in "else" part. -
How to let users download json of Django detail page context object
I build an elaborate context for a DetailView, with data from the model instance and an Elasticsearch query. It renders to a template fine, iterating through data in context['payload'] and context['traces'] lists. If I display {{ payload }} and {{ traces }}, I can see all the data as raw JSON. I'd like to provide a button on the page to download that JSON as a file. I have tried copying my DetailView code as a simple View, and adding response lines at the top, generating the context, then writing to the response and returning it. response = HttpResponse(content_type='text/json') response['Content-Disposition'] = 'attachment;filename="place-full.json"' ... code to build context ... response.write(context['payload']) response.write(context['traces']) return response I run that view from a new url path('<int:id>/full', views.placeFull, name='place-full') and get the following Value error: "The view places.views.placeFull didn't return an HttpResponse object. It returned None instead." -
Is it possible to swap FileField's filename during download/referencing on FE?
I'm using Django+DRF to allow upload/keep/serve user uploaded asset files. I need to let users to download the uploaded assets later. Upon a file upload I need to md5-hash its real name and save it to filesystem with that hash as the filename. Then, when the user wants to download/view it on FE, say he's uploaded a file 'cute_cat.jpg', I want him to get the file named 'cute_cat.jpg' and not 3c808e77fc1b0aee4435533690be458d (the name is one problem, the other one is that browser serves files w/o extensions as application/octet-stream and I want it to render '.jpg' (originally) files as images) I feel that I need to inject a HTTP header with 'Content-Disposition: attachment; filename=cute_cat.jpg' (I'm storing the real filename in DB) somewhere on the way to DRF's Response(), but I'm not sure at which point I'm to do this and even if it's possible... I've tried a bunch of stuff, mainly implementing custom fields for the serializer and injecting a custom URL there, but obviously that's not the way to it, because there's nowhere to inject headers to a text URL and there's no point trying to output a Request object with headers in an API view... This is my model: … -
sending dynamic mail with django
I am trying to send mail with form field inside html table . mail function is working but how can i include table: views.py: from django.shortcuts import render from main_site.models import artist from django.urls import reverse_lazy from .forms import BookartistForm from django.core.mail import send_mail def artist_booking(request): if request.method == "POST": form = BookartistForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] number = form.cleaned_data['number'] artist_name = form.cleaned_data['artist_name'] artist_category = form.cleaned_data['artist_category'] #event_type = form.cleaned_data['event_type'] date = form.cleaned_data['date'] budget = form.cleaned_data['budget'] location = form.cleaned_data['location'] description = form.cleaned_data['description'] print(name,email,number,artist_name,artist_category,date,budget,location,description) send_mail('Celebbizz Enquiry', '<html> <table> <tr> <th>Contact</th> <th>Details</th> </tr> <tr> <td>name</td> <td>email</td> </tr> </table> </html>' , 'admin@celebizz.com', ['nedinemo@daily-email.com'], fail_silently=False ) form = BookartistForm return render(request,'main_site/book_artist.html', {'form': form}) I'm trying to send mail with all these fields. im trying to add html table inside message filed it doesn't work -
Django: queryset using __gte shows wrong results after serialization
I'm facing an extremely weird issue while showing filtered results. Here's my api method: ... @list_route(methods=['GET'], url_path='internal-users') def internal(self, request, *args, **kwargs): users = models.User.objects.internal_users() data = self.get_serializer(users, many=True, context={'request': request}).data return response.Ok(data) ... Here's the internal_users() call of User model: ... def internal_users(self) -> Union[QuerySet, List['User']]: queryset = super(UserManager, self).get_queryset() queryset = queryset.filter(role_policy__gte=constants.UserRolePolicy.editor) # role_polict >= 63 return queryset ... Up until this point, the control -> shows the correct query formation and results. ... @list_route(methods=['GET'], url_path='internal-users') def internal(self, request, *args, **kwargs): users = models.User.objects.internal_users() # -> correct results data = self.get_serializer(users, many=True, context={'request': request}).data return response.Ok(data) ... However, as soon as I pass my objects to serializer in the next line, the results automatically reduce to only those users with role_policy EQUAL TO 63. Here's the serializer: class UserListSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = [ 'id', 'uuid', 'email', 'given', ... 'phone', ] What could be the issue? Please help. -
Why is Django ORM explain() function not giving expected output?
I'm trying to understand how the .explain() function works in Django ORM. The official documentation here says this. print(Blog.objects.filter(title='My Blog').explain()) gives below output. Seq Scan on blog (cost=0.00..35.50 rows=10 width=12) Filter: (title = 'My Blog'::bpchar) But if I try to print the same thing in my local Django shell, it is giving me different output like below. print(OCUser.objects.all().explain()) gives SIMPLE alyssa_ocuser None ALL None None None None 2853 100.0 None which is not similar to the one in the official documentation. I'm not sure what this SIMPLE, and all those None values are. Can someone please explain? Am I doing something wrong? Please leave a comment before downvoting the question. Python: 3.7.3 Django: 2.1.5 Mysql: Ver 14.14 Distrib 5.7.26 -
Django 1.11: URL function in template not working as expected
I've created 2 test apps, test1 and test2, and added the same functions in the views and same entries in the url files. The problem is that it does not matter which app you access, the same link, appname/link, is shown as the href. Does not matter if I access http://127.0.0.1:8000/test1 or http://127.0.0.1/test2, the link will always be "Test Link" Using the syntax url 'appname:link' does work, and sending an extra parameter to the html template to use the app name does work, but how can it be addressed only to use url 'link' Project urls: from django.conf.urls import include, url from django.views import generic from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^test1/', include('test1.urls')), url(r'^test2/', include('test2.urls')), ] test1 url: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'testapp/', views.testapp, name='testapp'), ] test2 url: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'testapp/', views.testapp, name='testapp'), ] test1 views: from django.shortcuts import render def index(request): return render(request, 'testme.html') def testapp(request): return render(request, 'testme.html') test2 views: from django.shortcuts import render def index(request): return render(request, 'testme.html') def testapp(request): return render(request, 'testme.html') testme.html: <a href = {% url 'testapp' %}>Test … -
Django setting media storage in settings issue
In my development.py settings I have the following: from django.core.files.storage import FileSystemStorage ... MEDIA_STORAGE = FileSystemStorage(location='/Users/myuser/myfolder') and in my staging.py settings I have this: from django_s3_storage.storage import S3Storage ... MEDIA_STORAGE = S3Storage(aws_s3_bucket_name=DOCUMENTS_BUCKET) The development.py settings file causes no issues and storing files works fine. However, importing the staging settings breaks on this line, MEDIA_STORAGE = ... so it cannot build. I had the exact same line outside the settings file, in the models.py where it's used. It worked normally. Should it be written differently if it's extracted into settings? -
IN Django IF ELSE Not Working within For Loop
for product in products: for dess in peice: for cell in sell: try: if product == dess: print(123) else: if product == sell:: print(456) else: print(nothing) except: pass i try to run this type of for loop with if else. but if 1st statement run then out from loop and not show any result. can you check what is issue ? -
Related posts by tag name
i want to show related posts by tag name However i got the error " get() returned more than one Tag -- it returned 2!" def post_detail(request,slug): post=get_object_or_404(Post,slug=slug) comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date') comment_count=len(Comment.objects.filter(post=post, statusc=2)) tag=get_object_or_404(Tag,post=post) related_item=Post.objects.filter(tag__tag_name__icontains=tag.tag_name,status=2).order_by('-created_date').distinct()[:3] -
Changing DateTime localization in Open Edx Bitnami edition
I want to change all DateTime values inside all pages in an Open Edx system (Bitnami release Ironwood 2.0) to Persian format. I found two ways to do that: 1- Add a new python module called 'django-jalali-date' at https://github.com/a-roomana/django-jalali-date, and also follow the instructions prepared at https://openedx.atlassian.net/wiki/spaces/AC/pages/30965856/How+to+add+a+new+feature+to+LMS+or+Studio, section How to add a new Django app to the edX platform. 2- Using http://ui-toolkit.edx.org/utilities/date-utils/ In option 1, I copied the 'jalali_date' folder to /opt/bitnami/apps/edx/edx-platform/openedx/features/jalali_date and added ('jalali_date', None) in OPTIONAL_APPS section in /opt/bitnami/apps/edx/edx-platform/lms/envs/common.py. Then I tried to use this module in my view by: from jalali_date import datetime2jalali, date2jalali. Unfortunately, I catch Internal Server Error, which says ImportError: No module named jalali_date. In option 2, I couldn't find any relevant help, so I have no idea how to use this library. Any help would be greatly appreciated. -
Django ORM Search Multiple Conditional Query
I have a problem when I want to search my queryset with multiple conditional. In my database, the hscode saved as "0105.14.90". I need to search the hscodes with following this query "01051490". eg: >>> query = '0105.14.90' >>> HSCode.objects.filter(hscode=query) <QuerySet [<HSCode: 0105.14.90>]> >>> query = '01051490' >>> HSCode.objects.filter(hscode=query) <QuerySet []> The bad think I can do, is look like this: hscodes = [] query = '01051490' for hscode in HSCode.objects.order_by('-id'): if query.isdigit() and hscode.hscode == query: hscodes.append(hscode) elif hscode.hscode.replace('.', '') == query: hscodes.append(hscode) How can handle it with ORM only? >>> query = '01051490' >>> HSCode.objects.filter(Q(hscode=query) | Q(???)) <QuerySet [<HSCode: 0105.14.90>]> -
attributeerror 'functools.partial' object has no attribute '__name__'
am using django 2.2 and python 3.7, am trying to make a decorators.py function called ajax required and am getting this error on the cmd once i run the server attributeerror 'functools.partial' object has no attribute 'name' decorators.py from django.http import Http404 def ajax_required(function): def wrap(request, *args, **kwargs): if not request.is_ajax(): raise Http404 return function(request, *args, **kwargs) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap -
Finding APIs in Django projects
I am new to the use of APIs, so kindly ignore if something sounds unusual. I have been shared a Django project and I need to modify some of the API whose URL is given to me. I tried looking at urls.py and found some URL matching with those that need to be modified. How to find other APIs in my Django project? -
When I PATCH a Boolean field, the update is reflected in the database but not the JSON output, why? (Django Rest Framework Serializer)
Assuming I have to override the update method in DRF's ModelSerializer - whenever I run PATCH to update a Boolean field from False to True, it will not be reflected in the JSON output. But when I check it is reflected in the SQLite database. Then, I run PATCH or GET to query data again, only then will the change show in the JSON output. Why does this happen and is there a way for the change to be reflected in the JSON body output immediately? The code below shows a stripped down version of my JobSerializer class. class JobSerializer(serializers.ModelSerializer): class Meta: model = Job fields = ( 'slug', 'student', 'service', 'time_slots', 'tutor_accept', ) def update(self, instance, validated_data): instance.tutor_accept = validated_data.get('tutor_accept', instance.tutor_accept) instance.save() return instance -
Django management for authentication session
I am researching into how I can use Django to manage the authentication session of users. I am new to the topic, so I would really appreciate as many details as you can provide. Basically, I will have some users logging in with the company credentials (username and password). Then, Django gets the "OK" from SecAuth and then I need to figure out how to manage the user session, once they are in. Specifically, the top 2 things I need to find out are how to: Manage token life cycle in Django Manage permissions to certain APIs in Django Optionally, if anyone can assist, I need to find out how to: Support some APIs without authentication Lock down other APIs with authentication Lock GUI down as per APIs Thank you very much in advance! :)