Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DeleteView form loads, but does not delete item
I tried implementing deleteview, however, while the form and page loads and the buttons are fine and redirects me since I put an action within the form, it does not delete the data at the end. I have been stuck at this for hours, please help me! Competencies model class Competencies(models.Model): employee = models.ForeignKey(Profile, blank = False, null = True, on_delete = models.SET_NULL) competency_category = models.ForeignKey(competency_category, blank = False, null = True, on_delete=models.CASCADE) . . def __str__(self): return self.summary Views.py - DeleteView class from django.views.generic import DetailView, DeleteView class Competencies_Delete(DeleteView): model = Competencies template_name = 'GnC/HuNet_DeleteDGC.html' def get_object(self): id = self.kwargs.get("pk") return get_object_or_404(Competencies, id = id) def get_success_url(self): return reverse('GnC:User_GnC') Html file that onclick 'Delete', allows deletion {%for competencies in Personal_competencies_list%} <tr> <td><a href = '../allusers/{{competencies.id}}/DeleteC'>Delete</a></td> </tr> {%endfor%} HuNet_DeleteDGC.html {%extends 'utilitypage.html'%} {%block content%} <form action="{% url 'GnC:User_GnC'%}" method='POST'> {%csrf_token%} <h4>Do you want to delete "{{object.summary}}"?</h4> <p><input type ='submit' value = 'Confirm'></p> <p><a href="{% url 'GnC:User_GnC'%}">Cancel</a></p> </form> {%endblock%} urls.py app_name = 'GnC' urlpatterns = [ path('allusers/<int:pk>/DeleteC', views.Competencies_Delete.as_view(), name ="Delete_User_Competencies") ] -
What is IAP (Identity Aware Proxy) ? How does it help a company to use web apps privately?
What is IAP (Identity Aware Proxy)? How does it help a company to use web apps privately throughout the world? What is the relation between GCP App Engine and IAP? -
Django Allauth register user after form saved
I'm working on one project in Django, and I stacked with one think. I need to create account for user and send email with password or generate password to his email that added in form. I'm using Django AllAuth for register/login accounts This is my model : class Atrakcje(models.Model): active = models.BooleanField(default=False) user = models.ForeignKey('authentication.CustomUser', on_delete=models.CASCADE) tytul = models.CharField(max_length=20) opis = models.TextField() kategoriaa = models.ForeignKey(AtrakcjeKategoria, on_delete=models.CASCADE, related_name='lista') adres = models.CharField(max_length=250) wojewodztwo = models.CharField(max_length=30) miasto = models.CharField(max_length=300) kodpocztowy = models.CharField(max_length=20, blank=True, null=True) telefon = models.IntegerField(blank=True, null=True) zdjecie = models.ImageField(upload_to='zdjecie/%Y/%m/%d', null=True, blank=True) email = models.EmailField(blank=True, null=True) strona = models.CharField(max_length=150, blank=True, null=True) facebook = models.CharField(max_length=150, blank=True, null=True) zaswiadczenia = models.ImageField(upload_to='zaswiadczenia/%Y/%m/%d', null=True, blank=True) wideo = models.CharField(max_length=300, null=True, blank=True) cena = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) free = "Ogłoszenie jest darmowe i na zawsze." pakiet1 = "Ogłoszenie premium na 7 dni." pakiet2 = "Wyróżnienie premium na 30 dni." pakiet3 = "Premium 1 rok." PAKIET_CHOICES = [ (free, 'Ogłoszenie jest darmowe i na zawsze.'), (pakiet1, 'Ogłoszenie premium na 7 dni.'), (pakiet2, 'Wyróżnienie premium na 30 dni.'), (pakiet3, 'Premium 1 rok.'), ] pakiet = models.CharField( max_length=50, choices=PAKIET_CHOICES, default=free ) rodzic = 'Dla rodziców.' dzieci = 'Dla dzieci.' oba = 'Dla dzieci i rodziców.' DLA_CHOICES = [ (rodzic, 'Dla … -
highstockchart range selector x axis date is displaying only jan 8 1970 to jan 19 1970
i have a data's from 1931 to yesterday in db. i am using python django models for getting data and disply the highstock. the chart is displaying only particular 15 days in x axis and range selector is also not working. here i have attached the jsfiddle code for your refernece.....any help thatks a lot ...strucked in this issues for last 2 days.... Highcharts.stockChart('container', { chart: { type: 'line' }, rangeSelector: { allButtonsEnabled: true, selected: 2 }, title: { text: '% of S&P 500 members above their 50 dma' }, yAxis: [{ lineWidth: 1, height :100, opposite: true, tickposition:'outside', visible:true }, { lineWidth: 0, height :100, opposite: true, tickposition:'outside', top :170, visible:true, }], series: [{ yAxis: 0, name: 'S&P 500', data: {{ sp500_series }}, color: 'green', tooltip: { valueDecimals: 2 } }, { yAxis: 1, xAxis:0, y :-30, name: 'dma50', data: {{ dma50_series }}, color: 'red', tooltip: { valueDecimals: 2 } }] }); the data samples are series: [{ yAxis: 0, name: 'S&P 500', data: [ [ 637266600.0, 336.0 ], [ 637353000.0, 336.87 ], [ 637439400.0, 338.07 ], [ 637525800.0, 341.91 ], [ 637785000.0, 343.53 ], [ 637871400.0, 341.57 ], ....... ........ ...... -
Updating the output field in Django Form on submission
I am building a translator web app using Django(I'm using PyCharm) and I'm fairly new to Django. The current status of my code is like this: forms.py: from django import forms import googletrans languaged = googletrans.LANGUAGES languagel = list(languaged.items()) class TransForm(forms.Form): enter_text_to_translate = forms.CharField( max_length=15000, widget=forms.Textarea(), help_text='Type here' ) translate_to = forms.ChoiceField(choices=languagel, required=True) translated_text = forms.CharField( max_length=15000, widget=forms.Textarea, required=False, disabled=True ) def clean(self): cleaned_data = super(TransForm, self).clean() enter_text_to_translate = cleaned_data.get('enter_text_to_translate') translate_to = cleaned_data.get('translate_to') if not enter_text_to_translate and not translate_to: raise forms.ValidationError('This field cannot be empty')''' views.py: from django.shortcuts import render from django.http import HttpResponse from .transForms import TransForm def index(request): if request.method == 'POST': form = TransForm(request.POST) #if form.is_valid(): #code to insert? else: form = TransForm() return render(request, 'index.html', {'form': form}) urls.py: urlpatterns = [ re_path(r'^index/$', views.index, name='index'), ] index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" novalidate> {% csrf_token %} {% if form.non_field_errors %} <ul> {% for error in form.non_field_errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} {% for hidden_field in form.hidden_fields %} {% if hidden_field.errors %} <ul> {% for error in hidden_field.errors %} <li>(Hidden field {{ hidden_field.name }}) {{ error }}</li> {% endfor %} </ul> {% endif %} {{ … -
How to do a custom redirection on AllAuth Social Account Signup
I have tried to do the following, but neither redirect nor render works: from allauth.socialaccount.adapter import DefaultSocialAccountAdapter, get_account_adapter from allauth.account.adapter import DefaultAccountAdapter from django.shortcuts import render class SocialAccountAdapter(DefaultSocialAccountAdapter): def __init__(self, request=None): DefaultSocialAccountAdapter.__init__(self, request) def save_user(self, request, sociallogin, form=None): """ Saves a newly signed up social login. In case of auto-signup, the signup form is not available. """ print('saving user') u = sociallogin.user u.set_unusable_password() if form: get_account_adapter().save_user(request, u, form) else: get_account_adapter().populate_username(request, u) sociallogin.save(request) print('right before redirect') return render(request, 'accounts/signup.html', context={'title': 'Edit Profile', 'register_update': 'Update'}) Only an ImmediateHttpResponse(redirect('url')) works, but then it redirects to the login page. Signals does not work either. -
Image not displaying on iOS devices (AWS S3, Django)
My scheduling app displays a thumbnail of the user at the top of the page. On desktop and Android devices, I'm having no problems at all. But on iOS devices (Chrome, Safari), the image does not show. The browser console does not throw any error so I'm struggling to figure out where the issue is coming from... See the app live here. Try on iOS vs Android and you'll see the difference. I'm using S3 buckets for storage and I've set up the bucket policy to public like so: { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::rentq-admin/*" } ] } Also, the image URL clearly works (see for yourself). Any suggestion? -
Django Rest Framework fetching data via serialisers via 3 tables
I am using drf and I am stuck with a simple scenario. Below are details about my app. Below are my Models:- class Service(TimeStampedModel): name = models.CharField("name of service", max_length=64) def __str__(self): return self.name class Events(TimeStampedModel): name = models.CharField("Expertise", max_length=100) organizer = models.CharField('Event Organizer', max_length=100) location = models.CharField('Event Location', max_length=100) title = models.CharField('Event Title', max_length=100) description = models.TextField('Event Description', max_length=100) time = models.DateTimeField('Event Time') is_active = models.BooleanField('Event Live') image = models.URLField('Event Url', blank=True) def __str__(self): return self.name class ServiceEventMap(TimeStampedModel): service=models.ForeignKey(Service, on_delete=models.CASCADE, related_name='service_event') event=models.ForeignKey(Events, on_delete=models.CASCADE, related_name='event') Below are my Serializers:- class EventSerializer(serializers.ModelSerializer): class Meta: model = Events fields = "__all__" class ServiceSerializer(serializers.ModelSerializer): service_event = serializers.SlugRelatedField(slug_field='event_id', many=True, read_only=True) class Meta: model = Service fields = '__all__' class ServiceEventMapSerializer(serializers.ModelSerializer): class Meta: model = ServiceEventMap fields = '__all__' I want my final data as:- { "id": , "service_event": [ { "id":, "name": "", "organizer": "", "location": "", "title": "", "description": "", "time": "", "is_active":, "image": "" } ], "createdOn": "", "modifiedOn": "", "name": "" }, How can I achieve this simply by using serializers, without an extra for loop or may be overriding ? I know I can achieve this via overriding to_representation method. Is that a right way or can we do something … -
Django Model Field Based on Previous Record Value
I am developing my first django project, building a web-based service request system for an engineering/production environment. I am building the request model, which has a field (request number) that needs to look at the last record's year field. If the new record is the same year, then the next sequential number is assigned. Otherwise, the request number needs to reset to 0001. I am using mySQL for the database. I am having difficulties understanding how to write the code to look at the previous record and take action accordingly. I can't seem to find any conversations on this. Either I'm not looking hard enough or not doing something right? Help! Thank you! -
Multiple Many-to-one relationships?
I am working on a django project following an old guide from CoreyMSchafer (https://www.youtube.com/watch?v=UmljXZIypDc&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p), who builds a django blog application. After finishing the tutorial he created I wanted to take it a step further. In the videos he creates posts, but he does not create a way for users to comment. I want to add this, but am running into a bit of idea block. My first thought is to continue the method he employed for the posts, which would be establish a one to many relationship with the user and the post, as below. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=1200) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): title = models.CharField(max_length=100) content = models.TextField(Max_length=1200) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) base_post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.title my concern with this would be that django does not support multiple many to one relationships, any thoughts and ideas are helpful. -
Django FileField - Set S3 url without upload
I am using Amazon Polly to generate text-to-speech mp3 files. These files are automatically added to a bucket and I want to save the url to a model's FileField without uploading an object. Can this be done? -
Running django factory in a loop doesnt create the required number of instances when the loop is run for really long
So, consider the sample model: class TestModal(models.Model): name = models.CharField(max_length=255) and the related factory created as: class TestModalFactory(factory.django.DjangoModelFactory): class Meta: model = TestModal Now, the problem is if I am creating 3000 instances in a loop as shown below: for _ in range(3000): TestModalFactory() It doesn't create 3000 instances but creates somewhere around 2950 instances of TestModal. I would love it if someone could help. -
I cannot show my image in my django HTML template
I have this model: class MyModel(Model): other_field = CharField(max_length=200) image = ImageField(upload_to='images/', null=True, blank=True, ) I have this in my project settings file: MEDIA_URL = '/media/' # new MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # new I also have an "images" folder in my media folder. These are the address of some of the files. To ensure you everything is ok: -myproject>myproject>settings.py -myproject>media>images>myimage1.png -myproject>media>images>myimage2.png I enter into the shell Python manage.py shell Then: from myapp.models import MyModel model_ins = MyModel.objects.get(id=1) model_ins.image.url It returns : '/media/images/myimage1.png' I have this HTML Template (simplified): {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <img src="{{ mymodel_ins.image.url }}"> </body> </html> it shows me no image. What is the reason? -
Python Django - Upload a Picture to see in a browser in a dev-mode
I'm trying to develop a blog website in a dev-mode in my localhost. When I'm trying to review my profile pictures in browser right after I upload my urls.py and settings.py; I'm havving error in the bottom. I'have tried other solutions mentioned in similar topics but those didnt' help. My base doc : https://docs.djangoproject.com/en/2.1/howto/static-files/#serving-files-uploaded-by-a-user-during-development Error: django.core.exceptions.ImproperlyConfigured: Empty static prefix not permitted Urls.py: from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('blog.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I've added this quote in settings.py: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDUA_URL = '/media/' -
How to get total time from a start and finish time using django TimeField?
So lets say I have to TimeField's in my model. One for start and one for finish. How would I get a total time from that? Basically I have this: class Job(models.Model): name = models.CharField(max_length=30) date = models.DateField() time_started = models.DateTimeField(blank=True, null=True) time_finished = models.DateTimeField(blank=True, null=True) def __str__(self): return self.name I want to do something like a model method or a view function maybe like this: def get_total_time(self): return time_finished - time_started But this isn't working. -
Sum Aggregation Across Several Foreign Key Relationships in Django 3.0 with Postgres
I have some Django models that are linked via Foreign Key relationships. An Estimate can have one or more Jobs, a Job can have one or more Works, a Work can have one or more Part. Part has a FloatField customer_cost Part looks like this: class Part(models.Model): work = models.ForeignKey(Work, related_name="parts", null=True, blank=True, on_delete=models.CASCADE) customer_cost = models.FloatField(blank=True, default=0) Work looks like this: class Work(models.Model): job = models.ForeignKey(Job, related_name="work_items", null=True, blank=True, on_delete=models.CASCADE) In a view for the Work model, I'm trying to annotate the response so that with each Work item, the summed customer_cost of all Part items that are linked to the same Estimate via Foreign Key relationships is returned. The following I believe is summing the same items multiple times (the returned result for jobs_total_parts_cost is much higher than I expected qs = qs.annotate(jobs_total_parts_cost=Sum('job__estimate__jobs__work_items__parts__customer_cost')) If I specify distinct=True on the Sum, it works, but not in the case where two Parts have the same customer_cost - e.g. if two parts have customer_cost 10 and one part has customer_cost 5, the result is 15 instead of 25. In other words, how can I specify that the value should only be summed once from each distinct part, rather than specifying that … -
Testing AJAX in Django
I want to test an AJAX call in my Django app. What is does is adding a product to a favorite list. But I can't find a way to test it. My views.py: def add(request): data = {'success': False} if request.method=='POST': product = request.POST.get('product') user = request.user splitted = product.split(' ') sub_product = Product.objects.get(pk=(splitted[1])) original_product = Product.objects.get(pk=(splitted[0])) p = SavedProduct(username= user, sub_product=sub_product, original_product = original_product) p.save() data['success'] = True return JsonResponse(data) My html: <form class="add_btn" method='post'>{% csrf_token %} <button class='added btn' value= '{{product.id }} {{ sub_product.id }}' ><i class=' fas fa-save'></i></button My AJAX: $(".row").on('click', ".added", function(event) { let addedBtn = $(this); console.log(addedBtn) event.preventDefault(); event.stopPropagation(); var product = $(this).val(); console.log(product) var url = '/finder/add/'; $.ajax({ url: url, type: "POST", data:{ 'product': product, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { if (data['success']) addedBtn.hide(); } }); }); The problem is that I pass '{{product.id }} {{ sub_product.id }}' into my views. My test so far: class Test_add_delete(TestCase): def setUp(self): self.user= User.objects.create(username="Toto", email="toto@gmail.com") self.prod = Product.objects.create( name=['gazpacho'], brand=['alvalle'], ) self.prod_2 = Product.objects.create( name=['belvita'], brand=['belvita', 'lu', 'mondelez'], ) def test_add(self): old_saved_products = SavedProduct.objects.count() user = self.user.id original_product = self.prod.id sub_product = self.prod_2.id response = self.client.post(reverse('finder:add', args=(user,))), { 'product': original_product, sub,product }) new_saved_products = SavedProducts.objects.count() self.assertEqual(new_saved_products, … -
How to solve problem "Must be a valid json" - Django + Vue js
I try to create object in Django with vue js + axios but somehowe this not work for me. I try in two ways and always I see in vue dev tools empty data. When I fill the data model in vuedev tools I see "Invalid value "Must be a valid Json"". First way. I create a view that return jsonresponse. @login_required def save_embed(request): if request.method == "POST": form = SubmitEmbed(request.POST) if form.is_valid(): url = form.cleaned_data['url'] r = requests.get('http://iframe.ly/api/oembed?url='+ url + '&api_key=' + IFRAMELYKEY) data = r.json() serializer = EmbedSerializer(data=data, context={'request': request}) if serializer.is_valid(): embed = serializer.save() return JsonResponse(serializer.data, status=201, content_type="application/json", safe=False) return JsonResponse(serializer.errors, status=400) else: form = SubmitEmbed() return render(request, 'embed/embedadd.html', {'form': form}) Template: <script> new Vue({ el: '#app', delimiters: ['!!', '!!'], data () { return { url: "http://example.com" } }, methods: { formSubmit(e) { e.preventDefault(); let currentObj = this; this.axios.post('http://wege.local:8000/recipes/recipe/embed/add/', { url: this.url, }) .then(function (response) { currentObj.output = response.data; }) .catch(function (error) { currentObj.output = error; }); } } }); </script> Form: <div id="app"> !! url.title !! <form method="post" class="margin-bottom-25" @submit="formSubmit"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success-gradiant">Dodaj link</button> </form> </div> In the url field has been added v-model "url". as you can see … -
Django queries against model instances and their most recent related instances
Suppose there are two models: from django.db import models class Entry(models.Model): id = models.BigIntegerField(primary_key=True) fieldE1 = models.DateTimeField(null=True, blank=True) fieldE2 = models.IntegerField(null=True, blank=True) fieldE3 = models.CharField(max_length=255, null=True, blank=True) class EntryPosition(models.Model): entry = models.ForeignKey(Entry, on_delete=models.CASCADE, related_name='positions') date = models.DateTimeField() fieldP1 = models.DateTimeField(null=True, blank=True) fieldP2 = models.IntegerField(null=True, blank=True) fieldP3 = models.CharField(max_length=255, null=True, blank=True) I need to perform various queries that aim to select each Entry based on its own fields' values plus values from most recent EntryPosition's fields. Filtered items queryset should map to a structure containing both Entry and its most recent related EntryPosition, like this (not necessarily as a nested dict, but it should have one of these structures): { 'id': 415, 'fieldE1': '2020-05-05 10:00:00', 'fieldE2': 654654, 'fieldE3': 'Some text', 'latest_position': { 'id': 5485, 'date': '2020-06-12 23:02:54', 'fieldP1': '2020-06-12 20:46:00', 'fieldP2': 74, 'fieldP3': 'Some other text', }, } or { 'id': 415, 'fieldE1': '2020-05-05 10:00:00', 'fieldE2': 654654, 'fieldE3': 'Some text', 'latest_position__id': 5485, 'latest_position__date': '2020-06-12 23:02:54', 'latest_position__fieldP1': '2020-06-12 20:46:00', 'latest_position__fieldP2': 74, 'latest_position__fieldP3': 'Some other text', } How should I assemble my query in Django to obtain such a queryset? -
How to make flutter mobile app associated to a django webapp?
I have a django webapp, which is a repository for alumni. Users can sign up using the extended user model and fill-in multiple fields. Then there is a detail page for each user that shows their respective data. All this is built using function based views. This bit is fine. But I also want to make its corresponding mobile apps for android and ios hopefully in flutter otherwise react native. My question is, should I host this as it is, or there are some basic things that I already need in the code so I can make a REST API and connect mobile apps later? I don't really have any knowledge about mobile apps and connecting django's REST API? So please guide me in this regard. Thanks :) -
how can i get new point with point and radius in django
I have a point and radius and I want to get 4 new points in my point and radius. radius = 101 latitude = 54.3578545 longitude = 36.417484151 point = Point(float(latitude), float(longitude)) locations = Location.objects.filter(location__equals=(point, D(km=radius))) point.x + d or point.x + d.standard -
DRF read-write field ownership filter
How do I limit amount of instances that DRF API browser gives me on a FK field of some model? For instance, if I have object with an owner (which is an instance of User) that is being referenced by anotherobject, how do I filter possible object that appear in the POST page of anotherobject with objects that have owner == request.user? I've seen a lot of solutions but my models have relationship with depth > 1 and there's nothing DRY in those solutions. -
error comes on writing pip install psycopg2 in windows 10 to connect python with postgres for my django project
i am installing psycopg2 for my django project to connect with postgres but got following error . As a beginner i dont know much so please help when i run pip install psycopg2 on windows i got this error C:\Users\Aman>pip install psycopg2 Collecting psycopg2 Using cached psycopg2-2.8.5.tar.gz (380 kB) Using legacy setup.py install for psycopg2, since package 'wheel' is not installed. Installing collected packages: psycopg2 Running setup.py install for psycopg2 ... error ERROR: Command errored out with exit status 1: command: 'c:\users\aman\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Aman\AppData\Local\Temp\pip-install-8u0ripm3\psycopg2\setup.py'"'"'; file='"'"'C:\Users\Aman\AppData\Local\Temp\pip-install-8u0ripm3\psycopg2\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Aman\AppData\Local\Temp\pip-record-dasbftyv\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\aman\appdata\local\programs\python\python39\Include\psycopg2' cwd: C:\Users\Aman\AppData\Local\Temp\pip-install-8u0ripm3\psycopg2\ Complete output (22 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\psycopg2 copying lib\compat.py -> build\lib.win-amd64-3.9\psycopg2 copying lib\errorcodes.py -> build\lib.win-amd64-3.9\psycopg2 copying lib\errors.py -> build\lib.win-amd64-3.9\psycopg2 copying lib\extensions.py -> build\lib.win-amd64-3.9\psycopg2 copying lib\extras.py -> build\lib.win-amd64-3.9\psycopg2 copying lib\pool.py -> build\lib.win-amd64-3.9\psycopg2 copying lib\sql.py -> build\lib.win-amd64-3.9\psycopg2 copying lib\tz.py -> build\lib.win-amd64-3.9\psycopg2 copying lib_ipaddress.py -> build\lib.win-amd64-3.9\psycopg2 copying lib_json.py -> build\lib.win-amd64-3.9\psycopg2 copying lib_lru_cache.py -> build\lib.win-amd64-3.9\psycopg2 copying lib_range.py -> build\lib.win-amd64-3.9\psycopg2 copying lib__init__.py -> build\lib.win-amd64-3.9\psycopg2 running build_ext building 'psycopg2._psycopg' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out … -
Converting date into datetime not working?
I am trying to convert the date into datetime with some specific time with combine method but it didn't worked . It throws AttributeError. AttributeError: module 'datetime' has no attribute 'combine' import datetime from dateutil.relativedelta import relativedelta from django.contrib.admin.models import LogEntry from django.utils import timezone now = timezone.now() print(now) required_date = now.date() - relativedelta(months=3) # 3 months older date print(required_date) required_datetime = datetime.combine(required_date, datetime.time(09,00,00)) print(required_datetime) LogEntry.objects.filter(action_time__range=(required_datetime, now)).delete() -
Handling signals when an object with m2m relations is created
I wish to do the following. When a new project is created , i want to notify everybody that was assigned to the project that there's a new project available. Here is my simplified project model: class SalesProject(models.Model): sales_project_name = models.CharField(max_length=100) userProfile = models.ManyToManyField('UserProfile', blank=True) history = HistoricalRecords(excluded_fields=['version', 'project_status']) def __str__(self): return self.sales_project_name When a project is being created, i will send out the following signal : def CreateProjectNotification(sender, **kwargs): if kwargs['action'] == "post_add" and kwargs["model"] == UserProfile: for person in kwargs['instance'].userProfile.all(): #some check here to prevent me from creating a notification for the creator or the project Notifications.objects.create( target= person.user, extra = 'Sales Project', object_url = '/project/detail/' + str(kwargs['instance'].pk) + '/', title = 'New Sales Project created') The reason why im using the m2m_changed.connect instead of post_save is because i wish to access the M2M field , UserProfile to send out the notifications. Since the object would not be added to the through table at the point of creation , i can't use the post_save and instead i have to track the changes from the through table . problem With that said , this signal runs as long as the save() function is called and the model which changed …