Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to Integrate Mpesa API with a django website
I am trying to integrate mpesa to a django website where a user completes filling a form then proceeds to pay for the service to be offered using lipa na mpesa before proceeding with the next step. -
Intercooler JS not sending form data correctly on Safari
I am developing a social media-type web application, and so far everything has been working fine on Chrome and Firefox. I recently discovered a bug on Safari (both iOS and macOS) where form data is not correctly being sent when I send an AJAX request using intercooler JS. The issue was found first when I realized that Safari was not allowing friend requests to be accepted when people respond from their notifications area. Here is the relevant HTML for when people accept/deny a friend request from their notifications <form method="post" ic-post-to="{% url 'respond-request' item.sender.pk %}"> {% csrf_token %} <button name="accept" type="submit">Accept</button> <button name="decline" type="submit">Decline</button> </form> In my Django View, I do two two things whenever someone responds to a friend request: Remove the notification/friend request entirely Add the users as friends if and only if accept is in request.POST This is the relevant code # Remove notification notification = Notification.objects.get(receiver=request.user, sender=userProfile, action="friend_request_received") notification.delete() # Remove the request request.user.friend_requests_received.remove(userProfile) # If yes, then add to friends and remove from request if 'accept' in request.POST: request.user.friends.add(userProfile) This is working as intended on Chrome and Firefox. When someone clicks accept on the above HTML, the users become friends. When they click decline, then … -
django dashboard page and dynamic data acquiring
Hello everyone I am pretty new on django programming and on this forum as well. I hope you can give some advice on below. First a short background on what I am doing: I am implementing a data gathering system it uses a python-snap7 application do pull data from a PLC and stores in a sqlite3 database (both running in a windows VM). After that I would like to build a dashboard built in django that gather data from the database resident on VM and will accessed from company office network. The django application must run on Host computer. My questions: First question: How do I keep the charts on dashbord page updated together with database refreshing it when new data is pulled from PLC ? Second question: Is it possible to access the database in VM from the host based django application ? Thanks for your help! -
Django - Link to download CSV in template
Trying to figure out how to correctly create a download link to a csv file on my template. Views.py #this is the view that shows the html page (all queries work) def admin_view(request, mysite): context = dict() context["mysite"] = mysite.upper() group = whid.lower() + "-group" user = request.user.get_username() authorized = is_authorized(user, group) end_time = timezone.now() start_time = end_time.replace(day=1, hour=00, minute=00, second=00) error_message = ("You are not authorized to be in this page.) context['data'] = CheckIn.objects.filter(Date__range=(start_time, end_time)) today = datetime.datetime.now() context['today'] = today context['first_day'] = today.replace(day=1, hour=00, minute=1) #Calling the csv function here context['response'] = export_search_csv(start_time, end_time) if (authorized): return render(request, 'mykiosk/admin.html', context) else: return HttpResponse(error) #function to grab and create csv def export_search_csv(start_time, end_time): data = CheckIn.objects.filter(Date__range=(start_time, end_time)) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="export.csv"' writer = csv.writer(response) writer.writerow(['id', 'EmpID', 'BarID', 'Username', 'Type', 'Liability', 'Date']) for item in data: writer.writerow([item.id, item.EmpID, item.BarID, item.Username, item.Type, item.Liability, item.Date]) return response Template <a href="{{ response}}">export to csv</a> Then all I get is a <HttpResponse status_code=200, "text/csv"> when trying to access the link. I'm missing something, I'm just not sure what. Due to internal company regulations, I can't use the djqscsv library either. Any help is appreciated. -
Aggregating over annotated queryset with subqueries in Django 1.11
I'm trying to aggregate the total value of a shares model grouped by date. Looking at the Django docs I see I should be doing a call to .values('date') (so that Django does the annotation grouping the queryset by date) followed by my annotation. The queryset involves two subqueries: prices = Quote.objects.filter( date=OuterRef('date'), asset=OuterRef('asset') ).order_by().values('price') usd_prices = Quote.objects.filter( asset__ticker='USDCLP', date=OuterRef('date'), ).order_by().values('price') shares_data = DailyShares.objects.filter( account=account, date__gte=start_date, ).order_by().annotate( price=Subquery(prices), usd_price=Subquery(usd_prices), clp_value=Case( When( asset__currency=Asset.USD, then=F('quantity') * F('price') * F('usd_price') ), default=F('quantity') * F('price'), output_field=models.DecimalField(), ), ).values( 'date', ).annotate( total_value=Sum('clp_value') ) The problem is this throws a KeyError: 'clp_value', I can't access the annotation after the call to .values('date'). If I add clp_value to the .values() call, I'll break the group-by because Django will try and group by unique (date, clp_value) pairs which is not what I'm trying to do. Any ideas? -
django rest framework check if serializer received None object
Our endpoint can return from multiple models, all have something in common so they are mapped to an uniform response, e.g.: { "reference": "November15-Inbound-1", "note": null, "inbound_date": "2018-11-14", "inbound_lines": [ { "article_code": "VBP_A", "quantity": 1 } ] } Now it is possible that when doing a retrieve or update call that the object does not exist: try: return AppInbound.objects.filter(customer__code=self.customer.code).get(**kwargs) except AppInbound.DoesNotExist: return None This 'None' is then returned to our serializer, which yields the following result: { "reference": "", "note": "", "inbound_date": null, "inbound_lines": [] } Is there a way I can check whether or not the serializer received a None object as input? Without having to do specific code per endpoint like: if serialized_data['reference'] == "": raise Http404 -
How to display the second last object from DB in Django?
I have a model for news. It looks like: class Post (models.Model): title = models.CharField(max_length=50) body = models.TextField() image = models.ImageField(upload_to='news_image', blank=True) def __str__(self): return self.title views.py looks like: class PostListView(ListView): model = Post template_name = 'html/main.html' class PostDetailView(DetailView): model = Post template_name = 'html/post_detail.html' Each news has it's own url: urlpatterns = [ path('', views.PostListView.as_view(), name='main'), path('news/<int:pk>/', views.PostDetailView.as_view(), name='news_page')] I use django admin to add posts. On main.html I want to display title and image of the second last post from database. I also need a link to that post. <img src="?????" href="????"> <p>{{ ??? }}</p> How can I do it? -
Upload image in django and decoder jpeg not available
I'm trying upload image in my old django (1.0.4) project. It was working before but now I'm receiving error 500. Below is part of traceback: IOError at /gallery decoder jpeg not available Request Method: GET Request URL: http://myproject.com/gallery Exception Type: IOError Exception Value: decoder jpeg not available I have installed (to working with images): PIL==1.1.7 Pillow==2.6.1 I did also upgrade - pillow and pil: pip install Pillow==2.6.1 --upgrade Requirement already up-to-date: Pillow==2.6.1 in /usr/lib/python2.7/dist-packages Cleaning up... and pip install PIL==1.1.7 --upgrade Could not find any downloads that satisfy the requirement PIL==1.1.7 in ./venv/lib/python2.7/site-packages/PIL Downloading/unpacking PIL==1.1.7 Cleaning up... No distributions at all found for PIL==1.1.7 in ./venv/lib/python2.7/site-packages/PIL -
Django File Upload - File Missing on Validation
tearing my hair out trying to have users upload a file in Django via a form. forms.py class GPXForm(forms.Form): title = forms.CharField() gpxfile = forms.FileField() models.py class GPXFile(models.Model): title = models.CharField() gpxfile = models.FileField(null=True, blank=True) views.py def upload(request): if request.method == 'POST': form = GPXForm(request.POST, request.FILES) print(form.errors) ... gpx_upload.html <form action = "/catalog/upload/" method = "post" enctype = "multipart/form-data"> {% csrf_token %} {{ form }} <input type = "submit" value = "Submit"> </form> When trying to upload with a 'sample.txt' file form.error returns 'gpxfile - this field is required' I'm missing something obvious, any suggestions gratefully received! -
Autofill django summernote
I am submitting a form with summernote widget . My forms.py: from django import forms from .models import Task,Images from django_summernote.widgets import SummernoteWidget class StudentTaskForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control',' type': "text",'placeholder':'Enter Title'})) content = forms.CharField(widget=SummernoteWidget()) class Meta: model = Task fields = [ 'title', 'content', ] widgets = { 'content': SummernoteWidget(), } def clean_object(self): instance = self.instance class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Images fields = ('image', ) The ImageForm is a formset part of this Taskform and the form submission is happening successfully. I want the user to be able to edit a task if the task already exists. For this i want the summernote widget to prepopulate with the previously entered data (title,content,images).ANy way i can implement this? -
Unicode convertion problem in django view
I have a queryset in Django view : queryset = CourseTeacher.objects.filter(cls__uuid__in=uuidlist).annotate(teacher_fullname=Concat('teacher__name', V(' '), 'teacher__surname')) There are some characters that causes UnicodeDecodeError exception.Teacher_fullname or teacher_surname may have these characters. So that it gives below warning: Exception Type: UnicodeDecodeError Exception Value: 'ascii' codec can't decode byte 0xc3 in position 12: ordinal not in range(128) The string that could not be encoded/decoded was: John ��. YI I am trying to write this string to excell worksheet as below : worksheet.write(teachersrow, item['teacher_fullname'].encode('utf-8'), cellformat) .encode('utf-8') seems not solving the problem Using Django 1.9.5 and Python 2.7.5 -
JSON Error AttributeError: 'dict' object has no attribute 'body'
def player(request): #some codes here ................ req = json.loads(request.body) name = req.get('name',None) pos = req.get('position',None) ........ ........ def football(request): #some codes here ......... reqData = {"name":"David Beckham","position": "midfielder"} player(reqData) ......... ......... when I call the function player from football, I got an Attribute error: 'dict' object has no attribute 'body' Please help. All I need is change the reqData JSON request, so that this error will not be occur -
Get authenticated user in view decorator
I am trying to capture the audit trail of all the GET requests using a decorator but I have a problem capturing the authenticated user. I would like to get my authenticated user from the header which contains a JWT token that contains the user id. Suppose I have the following view: class UserViewSet(viewsets.ModelViewSet): authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = UserSerializer @audit_view_action(endpoint='/users/', http_method='GET', message=' viewed all users.', user=True) def get_queryset(self): return get_users(self.request.user) and the following decorator: def audit_view_action(endpoint, http_method, message, user): def decorator_func(func): def wrapper_func(request, *args, **kwargs): retval = func(request, *args, **kwargs) return retval return wrapper_func return decorator_func Is there a way to get the active user? I have tried getting it from the request request.context['request'] but the request is only a UserViewSet object and doesn't have a context attribute. -
Django models / View / admin
How to make a that can view calculate data form multiple models, them make the data appear in the any django-admin models page? I have multiple models and one gets its data from them using models.ForeignKey I need to make an accounting field that calculate some math based on the choices of the ForeignKey fields. -
Extented templates and css in django, edit single html mark in css
I have base.html that I extend in my child.html. Now I need to change font-size and color of mark in this child.html view but it uses css connected to base.html Ofc I can copy all content from base.css create new child.css and there edit just this lines for mark but denied "extend" thing. What should I do ? Example code looks base.html {% block content %} <a href="{% url 'test' %}">test</a> {% endblock %} child.html {% extends 'base.html' %} . . . {% block content %} <a id="test" href="{% url 'test' %}">test</a> {% endblock %} base.css here is normal mark . . . #test{ color: #ffffff; font-size: 17px; } . . . child.css here is changed mark #test{ color: #a0a0a0; font-size: 19px; } -
Can't Render base64 file using FileResponse or StreamingHttpResponse, works using HttpResponse
I am saving my file in base64 in database and then trying to render it using Django view. file_obj = AttachmentData.objects.filter(id=file_id) file_data = base64.b64decode(file_obj.attachment_file) bytes_out = BytesIO() bytes_out.write(file_obj) response = HttpResponse(string_out.getvalue(),content_type=email_file_obj.mime_type) response["Content-Disposition"] = "attachment; filename={}".format(name) return response This code works fine, but When file is large then i need to use StreamingHttpResponse or FileResponse. The problem is these responses need file object as parameter. To create file i need to save it which i don't want as it will consume up my disk space. temp_file_obj = open(file_obj.file_name, 'wb') temp_file_obj.write(file_data) temp_file_obj.close() response = FileResponse(open(file_obj.file_name, 'rb'), content_type=email_file_obj.mime_type) I need a solution so that i send file without saving file on disk. -
Error in Running Django tests in visual studio
My tests are running fine in terminal but while trying to run tests in visual studio i got error of : Error of django.core.exceptions.AppRegistryNotReady: Apps aren't loaded My Visual studio Folder settting file is: "python.pythonPath": "/home/aditya/Maximl/Blast4/Server/syncopsenv/bin/python3.6", "python.unitTest.pyTestEnabled": false, "python.unitTest.nosetestsEnabled": false, "python.unitTest.unittestEnabled": true, "python.unitTest.debugPort": 3000, "python.unitTest.autoTestDiscoverOnSaveEnabled": true, "python.unitTest.pyTestArgs": ["."], "python.unitTest.unittestArgs": ["-v", "-s", ".", "-p", "*test*.py"] } -
Accessing object in perform_create when using many=true
How can I get object in perform_create() when I use kwargs['many'] = True? class CreateUserApiView(CreateAPIView): model = User ... serializer_class = CreateRequesterSerializer def get_serializer(self, *args, **kwargs): """ if an array is passed, set serializer to many """ if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super(CreateUserApiView, self).get_serializer(*args, **kwargs) def perform_create(self, serializer): obj = serializer.save( ..., created_by=self.request.user) obj.send_invitation() -
How to prefix keys for the cache in Django?
On my website every user can create a page. For example a user can add a custom color which is stored in the model. I don't want to clear the whole cache every time so I've added some helper functions to set a prefix for the keys. Is this the usual and good way to solve this problem? from django.db import models from django.core.cache import cache class Page(models.Model): # some fields ... # user # color # ... @property def _prefix(self): return f'{self._meta.object_name}_{self.pk}' def get_cache(self, key): return cache.get(f'{self._prefix}_{key}') def set_cache(self, key, value): return cache.set(f'{self._prefix}_{key}', value) def clear_cache(self, key): return cache.delete(f'{self._prefix}_{key}') -
Django Rest Framework url filter, import views error
I'm currently having trouble with writing Django Rest Framework filtering data by url. For some reason the problem seems to be when I import my views. The error points to the models which was working fine before I added the url filter in urls.py File "/home/jd_dhang/drf-demo/project/urls.py", line 5, in <module> from apps.core.views import SurgeryView File "/home/jd_dhang/drf-demo/project/apps/core/views.py", line 2, in <module> from .models import University, Student, SurgeryType File "/home/jd_dhang/drf-demo/project/apps/core/models.py", line 3, in <module> class University(models.Model): File "/home/jd_dhang/drf-demo/venv/lib/python3.5/site-packages/django/db/models/base.py", line 102, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class apps.core.models.University doesn't declare an explicit app_label and isn't in an applica tion in INSTALLED_APPS. Django==1.9.13, djangorestframework==3.6.0 project/urls.py **from apps.core.views import SurgeryView** urlpatterns = [ **url(r'^api/surgery/(?P<surgery_type>.+)/$', SurgeryView.as_view())**, ... ] project/apps/core/views.py from rest_framework import viewsets from .models import University, Student, SurgeryType from .serializers import UniversitySerializer, StudentSerializer, SurgeryTypeSerializer class StudentViewSet(viewsets.ModelViewSet): ... class UniversityViewSet(viewsets.ModelViewSet): ... class SurgeryView(viewsets.ModelViewSet): #(APIView): queryset = SurgeryType.objects.all() serializer_class = SurgeryTypeSerializer def get_queryset(self): queryset = SurgeryType.objects.all() surgery_type = self.kwargs['surgery_type'] return SurgeryType.objects.filter(surgery_type=surgery_type) Here are my models if it helps project/apps/core/models.py from django.db import models class University(models.Model): name = models.CharField(max_length=50) class Meta: verbose_name = "University" verbose_name_plural = "Universities" def __str__(self): return self.name class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) university = models.ForeignKey(University) class Meta: verbose_name … -
Refer to current model when submitting forms django
views.py form = StudentTaskForm(request.POST or None, request.FILES or None) if form.is_valid(): form.instance.user = User.objects.get(id=request.user.id) obj = form.save(commit=False) obj.student = request.user obj.todo = qs obj.level = instance obj.save() ImageFormSet = modelformset_factory(Images, form=ImageForm,min_num=0, max_num=3, validate_min=True,extra=3) if request.method == 'POST': formset = ImageFormSet(request.POST, request.FILES, queryset=Images.objects.none()) if formset.is_valid(): for form in formset.cleaned_data: try: image = form['image'] Images.objects.create(post=todo[0],image=image) except KeyError: pass return redirect('student:dashboard') else: formset = ImageFormSet(queryset=Images.objects.none()) forms.py: class StudentTaskForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form- control',' type': "text",'placeholder':'Enter Title'})) content = forms.CharField(widget=SummernoteWidget()) class Meta: model = Task fields = [ 'title', 'content', ] widgets = { 'content': SummernoteWidget(), } def clean_object(self): instance = self.instance class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Images fields = ('image', ) Im using formsets for saving images.A task may contain a maximum of three images. In models.py i have : class Task(models.Model): level = models.ForeignKey(Level, on_delete=models.CASCADE) todo = models.ForeignKey(ToDo, on_delete=models.CASCADE,related_name='todo') student = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) content = models.TextField() timestamp = models.TimeField(auto_now=True) datestamp = models.DateField( auto_now=True) like = models.ManyToManyField(User,related_name='user_likes',blank=True) is_verified=models.BooleanField(default=False,blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('student:dashboard') objects = PostManager() @property def comments(self): instance = self qs = Comment.objects.filter_by_instance(instance) return qs @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type class Images(models.Model): post = models.ForeignKey(Task, … -
Loging to other sites using temporary url
I'm making a password manager and was wondering how to generate a temporary link(that expires for example after 5 min) that takes login and password of the website that user has stored in the manager and allows someone to login into this account. Is there any way to do it because quite frankly I have no idea how to make it work. thanks for help :) -
Request is not resolve from mobile device to local server. show err address unreachable
Django project is running on IP - 0.0.0.0:8000. when i request the api url (http://10.5.50.147:8000/api/../) from mobile to this server. chrome shows the error. This site can't be reached. ERR_ADDRESS_UNREACHABLE. -
Foreign key constraint verification is slow
I have two models: class Model1(models.Model): # ... model2 = models.ForeignKey('Model2', null=True) class Model2(models.Model): # ... When any Model2 object or QuerySet is deleted, the database verifies the corresponding FK constraint for Model1's table, as it should. The problem is that this table is huge, so deleting many Model2 objects at once is unacceptably slow. The specific scenario I am handling guarantees the FK constraint will never be violated because all Model1 rows related with all Model2 rows at hand have already gotten deleted. How can I take advantage of this to speed up the deletion of Model2 objects? A very bad solution would be to temporarily disable the constraint, but this really should be a last resort. -
Urls with Categories slug and Post slug using Class Based View
I'm developing a simple blog to learn Django. I would like to have a path for each posts like this: /category-1/title-post /category-2/title-post etc.. Below urls.py from django.urls import include, path from .views import CategoryList, PostList, SingleCategory, SinglePost, SingleTag, TagList urlpatterns = [ path("", PostList.as_view(), name="list_post"), path("<slug:slug>", SinglePost.as_view(), name="single_post"), path("tags/", TagList.as_view(), name="list_tag"), path("tags/<slug:slug>", SingleTag.as_view(), name="single_tag"), path("categories/", CategoryList.as_view(), name="list_category"), path("categories/<slug:slug>", SingleCategory.as_view(), name="single_category"), ] And views.py from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Category, Post, Tag # Create your views here. class CategoryList(ListView): model = Category context_object_name = 'category_list' template_name = "list_category.html" class SingleCategory(DetailView): model = Category template_name = "single_category.html" class PostList(ListView): model = Post queryset = Post.objects.order_by('-id') context_object_name = 'post_list' template_name = "list_post.html" paginate_by = 4 class SinglePost(DetailView): model = Post template_name = "single_post.html" class TagList(ListView): model = Tag context_object_name = 'tag_list' template_name = "list_tag.html" class SingleTag(DetailView): model = Tag template_name = "single_tag.html" I don't understand how I can change the path "categories/" in "category-slug/". I would like to do a same thing for categories / , that must change in category-slug/post-slug. How I can do this using the Class Based View?