Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to move mail to specified folder in Outlook using Django and imaplib?
Im trying to move mail to a specific folder say "Tickets". Im unable to achieve that. Trying to achieve it using imaplib with Django. This issue im facing while accessing outlook mail. For Gmail im able to add label using +X-GM-LABELS adding code snippet below. Mails are getting deleted. Thanks for any help in advance for uid in id_list: imap.store(uid,'+FLAGS', '(Tickets)') imap.store(uid,'+FLAGS', '\Deleted') -
How to solve Django Axios Ajax Bad Request Error
Have two issues First: I get the following error in the terminal when i post comment Bad Request: /post/comment/ "POST /post/comment/ HTTP/1.1" 400 37 Second: body:formData returns empty JSON(i resolved this by directly assigning the JavaScript variable that stores form body content body:content) Just want to know why formData returns empty Here is the code for my project Model: class Comment(models.Model): body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) post = models.ForeignKey('Post',related_name="post_comment",on_delete=models.CASCADE) class Meta: ordering =['-created_on'] Form class PostCommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) View class PostComment(LoginRequiredMixin,FormView): form_class = PostCommentForm def form_invalid(self,form): if self.request.headers.get('x-requested-with') == 'XMLHttpRequest': return JsonResponse({"error": form.errors}, status=400) else: return JsonResponse({"error": "Invalid form and request"}, status=400) def form_valid(self,form): if self.request.headers.get('x-requested-with') == 'XMLHttpRequest': form.instance.author = self.request.user post = Post.objects.get(pk=self.kwargs['pk']) form.instance.post = post comment_instance = form.save() ser_comment = serializers.serialize("json", [comment_instance, ]) return JsonResponse({"new_comment": ser_comment}, status=200) else: return JsonResponse({"error": "Error occured during request"}, status=400) Url path('post/comment/', views.PostComment.as_view(), name='post-cmt'), JavaScript Ajax using Axios.js <script type="text/javascript"> axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; function createComment(formData) { console.log("Posting Comment"); axios.post("{% url 'post-cmt' %}", { body: content }).then(function(response) { console.log(response) }).catch(function(error){ console.error("Error", error); }); } const content = document.getElementById("id_body").value const cform = document.getElementById("comment-form"); cform.addEventListener('submit', function(e){ e.preventDefault(); if(content){ let formData = new FormData(cform); … -
'WSGIRequest' object has no attribute 'owner'
I am getting this error and I can't seem to figure it out. I tried changing the middleware, but that didn't seem to work. This is the error: The serializer field might be named incorrectly and not match any attribute or key on the WSGIRequest instance. Original exception text was: 'WSGIRequest' object has no attribute 'owner'. views.py import json from django.http import JsonResponse from rest_framework import viewsets, serializers from .models import * from django.views.decorators.csrf import csrf_exempt class CreateTodoRequest(serializers.Serializer): owner = serializers.IntegerField() title = serializers.CharField() class CreateTodoResponse(serializers.Serializer): id = serializers.IntegerField() owner = serializers.IntegerField() title = serializers.CharField() @csrf_exempt def create_todo_list(request): data = CreateTodoRequest(request) params = {'owner': data['owner'], 'title': data['title']} todo = models.List.objects.create(**params) serial = CreateTodoResponse(todo) return JsonResponse(todo.data, status=200) class UpdateListRequest(CreateTodoRequest): id = serializers.IntegerField() class UpdateListResponse(UpdateListRequest): """ """ @csrf_exempt def update_todo_list(request): data = UpdateListRequest(request) params = {'owner': data['user_id'], 'title': data['title']} rows_affected = models.List.objects.filter(id=data['id']).update(**params) todo_list = models.List.objects.get(id=data['id']) serial = UpdateListResponse(todo_list) return JsonResponse(serial.data, status=200) class DeleteListRequest(serializers.Serializer): id = serializers.IntegerField() @csrf_exempt def delete_todo_list(request): data = DeleteListRequest(request) models.List.objects.filter(id=data['id']).delete() return JsonResponse(True, status=200, safe=False) class CreateTaskRequest(serializers.Serializer): title = serializers.CharField() task_list = serializers.CharField() completed = serializers.BooleanField() due_date = serializers.DateTimeField() class CreateTaskResponse(CreateTaskRequest): """ """ def create_task(request): data = CreateTaskRequest(request) params = {'title': data['title'], 'task_list': data['task_list_id'], 'completed' : data['completed'], 'due_date' : data['due_date']} … -
Having "permission denied" when I try to upload image to /media/ dir, DJANGO
I setup django framework into apache server, normally there is no problem when I try to insert record to DB. But if I try to upload something into media dir, permission problem occurs. I already give the chmod -R 755 to /var/www/ project's parent folder. But still having the problem. settings.py STATIC_URL = '/static/' MEDIA_URL = "/media/" STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, "media") and .conf settings are below. <VirtualHost *:8001> ServerName example.com DocumentRoot /var/www/ Alias /static /var/www/example.com/src/static <Directory "/var/www/example.com/src/static"> Options FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> Alias /media /var/www/example.com/media <Directory "/var/www/example.com/media"> Options FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> ErrorLog /var/www/example.com/logs/apis_error.log CustomLog /var/www/example.com/logs/apis_access.log combined WSGIPassAuthorization On WSGIDaemonProcess example.com python-path=/var/www/example.com:/var/www/venv36/lib/python3.6/site-packages WSGIProcessGroup example.com WSGIScriptAlias / /var/www/example.com/src/wsgi.py <Directory /var/www/example.com/src> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Any idea what is the problem here? -
How do you query a model for an aggregate of a ForeignKey computed field
How do you query a model for an aggregate of a ForeignKey 'computed' (Autofield?) field I have two models: class Job(models.Model): name = models.CharField(…) class LineItem(models.Model): job = models.ForeignKey(Job, …) metric_1 = models.DecimalField(…) metric_2 = models.DecimalField(…) metric_3 = models.DecimalField(…) # Making this a @property, @cached_property, or the like makes no difference def metric_total(self): return (self.metric_1 + self.metric_2 * self.metric_3) In the view: class StackoverflowView(ListView, …): model = Job def get_queryset(self): return Job.objects .select_related(…) .prefetch_related('lineitem_set') .filter(…).order_by(…) def get_context_data(self, **kwargs): context_data = super(StackoverflowView, self).get_context_data(**kwargs) context_data['qs_aggregate'] = self.get_queryset() \ .annotate( # Do I need to Annotate the model? ).aggregate( # This works for any of the fields that have a model field type metric1Total=Sum('lineitem__metric_1'), metric2Total=Sum('lineitem__metric_2'), # This will error : # Unsupported lookup 'metric_total' for AutoField or join on the field not permitted. # How do I aggregate the computed model field 'metric_total'? metricTotal=Sum('lineitem__metric_total'), ) return context_data When I try to aggregate the computed field, I get the error: Unsupported lookup 'metric_total' for AutoField or join on the field not permitted.. How do I aggregate these special fields? -
Django Annotations
So I'm working on a website, and I want to have some kind of a summary page to display the data that I have. Let's say I have these models: class IceCream(TimeStampedModel): name = models.CharField() color = models.CharField() class Cupcake(TimeStampedModel): name = models.CharField() icing = models.CharField() So on this page, users will be able to input a date range for the summary. I'm using DRF to serialize the data and to display them on the view actions. After I receive the filter dates, I will filter out the IceCream objects and Cupcake objects using the created field from TimeStampedModel. @action(detail=False, methods=['get']) def dessert_summary(self, request, **kwargs): start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') cupcakes = Cupcake.objects.filter(created__date__range=[start_date, end_date]) ice_creams = IceCream.objects.filter(created__date__range=[start_date, end_date]) After filtering, I want to count the total cupcakes and the total ice creams that is created within that period of time. But I also want to group them by the dates, and display the total count for both ice creams and cupcakes based on that date. So I tried to annotate the querysets like this: cupcakes = cupcakes.annotate(date=TruncDate('created')) cupcakes = cupcakes.values('date') cupcakes = cupcakes.annotate(total_cupcakes=Count('id')) ice_creams = ice_creams.annotate(date=TruncDate('created')) ice_creams = ice_creams.values('date') ice_creams = ice_creams.annotate(total_ice_creams=Count('id')) So I want the result to be … -
Django migrations.RunSQL visibility to other connections during tests
I am creating a postgresql function in a migrations.RunSQL, and it gets created just fine. I have the default connection and another connection ('userdata') that, in this case, actually point to the same DB. The problem is that during tests, the function created in RunSQL is not visible to the 'userdata' connection. Is is visible to the default connection (which I'm guessing runs the RunSQL). Fine, I say, it's just in tests so I will close and reopen after migrations are run (by overriding setup_databases in my DiscoverRunner, for example) and then the 'userdata' connection will also see the new function. Alas, the ONLY place that the connections['userdata'].connect() call seems to actually have the desired effect is calling it actually in the test method (or in the classes being tested of course). The new function remains invisible if I do a connect() in the setup_databases or setUp for the TestCase. The same is true of connections.close_all(), which also only works in the test method. There seems to be some magic going on, with different connections being returned at different times. Is there a way to tell Django to reopen all stale connections that will work in tests? -
Field Serializers Django
I have a serializer with some custom fields and those fields depends on a specific query. The problem is that each time the serializer tries to get the value for this field It must perform the query to the DB. What about if the serializer is a many=True serializer?. class ExampleSerializer(serializers.ModelSerializer): field_one = serializers.SerializerMethodField() field_two = serializers.SerializerMethodField() field_three = serializers.SerializerMethodField() . . . def get_field_one(self, obj): try: # This is where i do the query query_result = obj.objects.filter(filter=self.context.get("filter").first() if query_result: # Do field one stuff except Exception: # Do exception stuff def get_field_two(self, obj): try: # This is where i do the query query_result = obj.objects.filter(filter=self.context.get("filter").first() if query_result: # Do field two stuff except Exception: # Do exception stuff def get_field_three(self, obj): try: # This is where i do the query query_result = obj.objects.filter(filter=self.context.get("filter").first() if query_result: # Do field three stuff except Exception: # Do exception stuff Is there a way to store that result inside a property in the serializer? Also, if I set a value in one of the serializer field, how do I retrieve and do some maths on another field in the same serializer? -
Integrate the JSON file via an API-Rest in MongoDB database
I generated a JSON file from Django to integrate it via an API-Rest in a MongoDB database. Generate a JSON file from Django: with open("fichier.json", "w") as out: data = serializers.serialize("json", User.objects.all()) out.write(data) data2 = serializers.serialize("json", Categories.objects.all() ) out.write(data2) the second step about integrating the JSON file via an API-Rest in a MongoDB database? I don't have any idea about doing it! Thanks for your help. -
Set field update in address url json django rest framework
I need update the field 'plan': The view @api_view(['GET','PUT']) def set_plan(request, nr_acc, nr_plan): plan = Plan.objects.get(pk=nr_plan) acc = Account.objects.get(pk=nr_acc) #return Response(plan.id) if request.method == 'PUT': #acc.plan.id = plan.id #acc.save() serializer = AccountSerializer(acc, data=request.data) if serializer.is_valid(): serializer.data['plan'] = request['plan'].id serializer.save() serializer_dict = serializer.data serializer_dict['message'] = "Consegui fazer o update do plano." return JsonResponse({'Conta':acc.id,'Novo plano': acc.plan.id}, status=200) else: return JsonResponse({'Conta':acc.id,'Novo plano': acc.plan.id}, status=200) return JsonResponse({'Conta':acc.id,'Novo plano': acc.plan.id}, status=200) In browser (http://127.0.0.1:8000/account/set-plan/1/1) I cant set update, the plan are with id 2, when i access the address http://127.0.0.1:8000/account/set-plan/1/1 dont update -
Function based view - dependent dropdown list
<script> $("#id_category").change(function () { var url = $("#newrequestForm").attr("data-sector-url"); // get the url of the load_cities view var categoryId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'scholar_category': categoryId // add the country id to the GET parameters }, success: function (data) { // `data` is the return of the `load_cities` view function $("#id_sector").html(data); // replace the contents of the city input with the data that came from the server } }); }); -
Is there a way to update an app config based on an overridden setting in a Django TestCase?
For example, if given a method that relies on the app config: def foo(): if apps.get_app_config('some_app').bar: return True Where some_app.bar is False by default, but I want to test it when it's True: class TestFoo(TestCase): @override_settings(BAR=True) def test_foo_enabled(self): # Fails because the app config isn't updated when using override_settings self.assertTrue(foo()) Is there a way to update the app config with the new setting from override_settings? Ideally, I want to avoid duplicating the app config setting in foo(): def foo(): if getattr(settings, BAR, False): return True -
How can I divide and set 2 decimal place in Django template?
I'm trying to do something like this: divide the product.sell_price by 3 and then use 2 decimal places. My code in Django template: {% widthratio product.sell_price 3 1 | floatformat:'2' %} If I only {% widthratio product.sell_price 3 1 %} everything goes OK but I need to insert 2 decimal places. Any help? Thank you! -
How to assert a IntegrityError properly in django?
folks. I'm trying to create a unit test to pass when an IntegrityError is raised. I tried to do this but it tells me that IntegrityError is not iterable: def test_create_company_with_duplicate_cnpj(self): with self.assertRaises(IntegrityError) as context: Company.objects.create(name=self.company.name, cnpj=self.company.cnpj) self.assertTrue('UNIQUE constraint failed' in context.exception) I did the "workaround" below and it passed. But is it correct or is there a different solution without using pytest? def test_create_company_with_duplicate_cnpj(self): with self.assertRaises(IntegrityError): Company.objects.create(name=self.company.name, cnpj=self.company.cnpj) -
GeoDjango with PostGIS - distance calculation is wrong
I'm trying to use GeoDjango with PostGIS in order to measure distances but the results I'm getting are off by 20%. For testing I chose 2 random points in the ocean: (40.607532, -72.829369) and (40.366040, -73.556856). To get the expected result I used 2 different methods: The google maps "measure distance" feature. My own python code using the great arc distance calculation. Both give me the same result of 41.71 miles. Django gives me 50.49. Here is my code: # models.py from django.contrib.gis.db import models class Location(models.Model): point = models.PointField(null=True) Then from the django shell: >>> from loc.models import Location >>> from django.contrib.gis.geos import Point >>> from django.contrib.gis.db.models.functions import Distance >>> loc = Location(point=Point(40.366040, -73.556856, srid=4326)) >>> loc.save() >>> pnt = Point(40.607532, -72.829369, srid=4326) >>> qs = Location.objects.annotate(distance=Distance('point', pnt)) >>> qs[0].distance.mi 50.4954671273202 -
Django - Using get_readonly_fields but getting 'NoneType' object is not iterable' when adding new record
here's the thing, if the X field (non required) has a value then none of the others fields can be edited (when editing). However, if this values is empty then all the other fields should go back to normal. I did that using this inside the app's admin.py def get_readonly_fields(self, request, obj=None): if obj: lb = obj.X if lb: return ['v','p','e'] else: return [] This works when you enter existing objects, however when adding a new instance I get the yellow page with the 'NoneType' object is not iterable' error. I'm aware this because the OBJ is null, when looking up for similar problems I found this is a django bug with get read only fields, apparently. Searched for solutions but they make that the created object can't be edited anymore (at least the ones I found). Is there a workaround or another method I can use? Thanks. -
How to count users if they have a product within a date range using Django ORM?
So let's say I have these 2 models: class User(models.Model): name = models.CharField() dob = models.DateField() class Product(models.Model): user = ForeignKey(User) created = models.DateTimeField() name = models.CharField() amount = models.DecimalField() Users can create a product, and it will save when that product is created. What I want to ask is, is it possible to count the number of users that have a product within a range of time? I'm using GenericViewSet for the views and created actions inside it to return the data. I want the views to return a data that looks like this: { 'data': [{ 'date': "2020-01-01", 'total_users': 10 }, { 'date': "2020-01-02", 'total_users': 17 }] } I understand that I can filter the products using a date range like this to get the products: Product.objects.filter(created__range=["2020-01-01", "2020-02-01"]) But how do I calculate the total users that have a product within that range? Is it possible to do annotations for this? Thanks in advance for your help! -
My django web app is holding on to old image data in memory. How can I clear it after every submit?
I have built a django app that asks for user input, then uses numpy and matplotlib.pyplot to generate graphs and display them in my web page. I'm not saving the data to disk, but rather saving it to memory using io and base64, which may be part of the problem. On first submit, I get something like this, which is exactly what I want, but then on subsequent submits, I never get rid of the old graphs and end up with something like this and this. Here is my views.py file: from django.shortcuts import render from .forms import NNInput import numexpr as ne import numpy as np import matplotlib.pyplot as plt import io import base64 from PIL import Image from .FeedForwardNN import FFNN # Create your views here. def ffnn(request): if request.method == 'POST': form = NNInput(request.POST) if form.is_valid(): cd = form.cleaned_data net = FFNN(1, 1, [cd['n'] for i in range(cd['m'])]) x = np.arange(-1, 1, .001) x.shape = (x.shape[0], 1) untrained = net.evaluate(x) fig_untrained = plt.figure(1) plt.xlabel('x- axis') plt.ylabel('y-axis') plt.title('Pre-Training NN (green) vs function') y = ne.evaluate(cd['func']) plt.plot(x, y, 'r', x, untrained, 'g') buf = io.BytesIO() fig_untrained.savefig(buf, format='png') im = Image.open(buf) buf2 = io.BytesIO() im.save(buf2, format='png') im_str = base64.b64encode(buf2.getvalue()).decode() data_uri … -
How to create a personalized tags in Django?
I have a value that I need to replace for example, the string is "https://www.test.com" and I want to change it into "https://test.com". -
Django form filter a class object by a foreign key
I have these models in models.py class Teacher(models.Model): Gym = models.ManyToManyField(Gym) class Student(models.Model): ... Gym = models.ForeignKey(Gym, on_delete=models.CASCADE) Teacher= models.ForeignKey(Teacher, on_delete=models.CASCADE) ... When creating a Student I have to choose a gym and a teacher, a teacher teaches on a gym, a Student has a Teacher from the Gym that the Student goes When creating a new Student in the forms, how do I select a Gym and filter only the Teachers of that Gym selected? -
Editing Django Wagtail Context
I am trying to add additional context to a home page model pulling from a separate app. The function already in the model is already handling a contact form on the page. I want to add blog posts from a portfolio app. Here is my function within my model: def serve(self, request, *args, **kwargs): from contact.forms import ContactForm from portfolio.models import PortfolioDetailPage context = super().get_context(request) context['posts'] = PortfolioDetailPage.objects.live().public() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): //form stuff try: //more form stuff except Exception as e: //more form stuff return render(request, 'contact/contact_page_landing.html', { 'page': self, 'contact': contact }) else: form = ContactForm() return render(request, 'home/home_page.html', { 'context': context, 'page': self, 'form': form }) In my template, I have the following: {% for post in posts %} <div class="row"> <div class="col-lg-4 col-md-4 col-sm-6"> {% image post.gallery_main_image fill-250x250 as blog_img %} <div class="latest__item"> <img src="{{ blog_img.url }}" alt=""> <h4><a href="{{ post.url }}">{{ post.gallery_name }}</a></h4> </div> </div> {% endfor %} </div> However, I am not getting any posts in my context. The form works properly. It seems this is an issue with the serve function in Wagtail already pulling my context and somehow I am not returning it properly but I cannot … -
Django: limit on permission_required size for TestCase? (PermissionRequiredMixin)
My test case raises a django.core.exceptions.PermissionDenied exception even though permission_required and user permissions seem to be set right. Here is the test case: def test_create(self): """ Test view for creating a new category """ response = self.client.get(reverse('category-create'), {'category': 1}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) Here are the relevant views: class AjaxMixin(PermissionRequiredMixin): """ AjaxMixin provides basic functionality for rendering a Django form to JSON. """ # By default, allow *any* permissions permission_required = '*' def has_permission(self): """ Override the default behaviour of has_permission from PermissionRequiredMixin. """ if self.permission_required == '*': return True else: return super().has_permission() class CategoryCreate(AjaxMixin, CreateView): """ Create view to make a new PartCategory """ # The problem is with 5 or more permissions, TestCase fails... no idea why! permission_required = ('part.add_part', 'part.add_bomitem', 'part.add_partcategory', 'part.add_partattachment', 'part.add_partsellpricebreak', # 'part.add_parttesttemplate', # 'part.add_partparametertemplate', # 'part.add_partparameter' ) If I comment 'part.add_partsellpricebreak', in the CategoryCreate view, the get request response code is 200 and no exception is raised by the test case. If I re-enable it, the test case breaks as stated above. The CategoryCreate view works exactly as intended though the project's UI (eg. permissions are well managed, independently of the size of permission_required). Any leads why is the test case failing when permission_required has … -
Django - Cannot locate images through '/media/'
I cannot seem to get images to work on my django project. I have created a "profile" model that is 1:1 with each user, and one of the profile fields is a profile picture. I have added the following to my settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I have added the following to my project urls.py: from django.conf import settings from django.conf.urls.static import static and the following after all my urlpatterns: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The image is saved in my root directory/media/profile_pics When I open the missing image in a new tab, I get a 404 error saying that no image could be found at, "http://localhost:8000/profile/profile_pics/ProfilePic.jpg" However, when I change MEDIA_URL = '/media/' to MEDIA_URL = '/profile/' the picture WILL load on my profile page, profile.html page with the 'profile/' url path, but the picture will not load on any other page. What am I missing? -
Creating Virtual environment issues
Im trying to create my virtual environment and I keep getting a permission denied getting sent back to me from git. im not sute if i understand how to bypass this and im working on windows, i tried some things but i still cant create my first venv. has anyone else has this issue? i figure it was because im not seen as the admin but idk now to establish myself as the admin to be able to do things like that. I just reset git but i can try everything again to take a screencap of the issues. Any help is appreciated! -
Django, how do I create a method that saves records from multiple "model" tables?
They help me understand. I have a model with two linked classes. I have two html views, one of them searches and in the other I save two data. Then in the html search view. I search for cod_pro, and then I can register the two new data in "var". Now what is my question, consult. First: What I understand is to fill the records from the html Record view. But: What I DO NOT understand is. How do I perform the method, to query the data from the view "camp", to register it in the view "var", in addition to the 2 new records.? Is there a method?. Please. Django, Python