Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: my test migration throws a Key Error but normal migration is fine. What's broken and how do I fix it?
Django test migration throws Key Error I get a Key error, but only when I do python manage.py test and not when I do python manage.py makemigrations or python manage.py migrate. Any suggestions how I can fix this? python manage.py test apps/userprofile Creating test database for alias 'default'... Got an error creating the test database: database "test_financetracker" already exists Type 'yes' if you would like to try deleting the test database 'test_financetracker', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/test/runner.py", line 629, in run_tests old_config = self.setup_databases(aliases=databases) File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/test/runner.py", line 554, in setup_databases self.parallel, **kwargs File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/test/utils.py", line 174, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/db/backends/base/creation.py", line 72, in create_test_db run_syncdb=True, File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 148, in call_command return command.execute(*args, **defaults) File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/financetracker/myvenv/lib/python3.7/site-packages/django/core/management/base.py", line 83, … -
User register page using (contrib.auth.models User) but facing Not Null Constraint Error
I am first to Django. I am making a registeration form only to facing NOT NULL constraint failed: blog_userprofile.user_id. i have been trying to figure out but i can not. Thank you for any help:) This is my models.py file from django.db import models from django.urls import reverse from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.PROTECT,blank=True) def __str__(self): return self.user.name This is my forms.py file from django import forms from .models import Post,Comment,UserProfile class UserProfileForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) username = forms.CharField(max_length=200) email = forms.EmailField() class Meta(): model = UserProfile fields = ['username','email','password'] And this is my views.py file from django.shortcuts import render from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect,HttpResponse from django.urls import reverse_lazy,reverse from django.views.generic import (TemplateView,ListView,DetailView) from django.views.generic.edit import CreateView,UpdateView,DeleteView from .models import Post,Comment,UserProfile from .forms import PostForm,CommentForm,UserProfileForm def register(request): registered = False if request.method == 'POST': user_form = UserProfileForm(request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True return HttpResponseRedirect(reverse('blog:user_login')) else: print('unvalid imformation') else: user_form = UserProfileForm() return render(request,'register/registration.html',{'user_form':user_form, 'registered':registered}) And this comment shows up IntegrityError at /signup/ NOT NULL constraint failed: blog_userprofile.user_id -
Bootstrap toggle is not a function
am actually developing an django application for warehouses an stockists. I am trying to get a list of stockist per warehouse in a list button. This button show a modal that make a query by an ajax consult with the name, position and permissions of all the stockists assigned to a specific warehouse. I want to show a toggle button from bootstrap in my modal, and i refresh the bootstrapToggle function and it show the next message Uncaught TypeError: $(...).bootstrapToggle is not a function Actually all the javascript code is this: var token = '{{csrf_token}}'; $('#Modal_list').on('show.bs.modal', function (event) { var button = $(event.relatedTarget); // Button that triggered the modal var urlToAjax = button.data('urlstockists'); console.log(urlToAjax); var recipient = button.data('pk'); // Extract info from data-* attributes console.log(recipient); $.ajax({ headers: { "X-CSRFToken": token }, url: urlToAjax, type: 'POST', data: {'id':recipient}, success: function(data){ console.log(data) var htmldata="" if(data.length==0){ htmldata += '<div class="h5 mb-0 font-weight-bold text-gray-800"> There are no assigned stockists </div>' }else{ for(var i = 0; i<data.length; i++){ htmldata += '<div class="card border-left-primary shadow h-100 py-2">\ <div class="card-body">\ <div class="row no-gutters align-items-center">\ <div class="col mr-2">\ <div class="h5 mb-0 font-weight-bold text-gray-800">Name: '+data[i].fields.name+'</div>\ <div class="h5 mb-0 font-weight-bold text-gray-800">Position: '+data[i].fields.position+ '</div>\ <div class="form-group">\ <label> Grant input\ <input type="checkbox" … -
Django: How to display foreign key objects of a model in manual form field as choices
So I have 2 models called Billing and Organization as shown below. Billing in the admin site works as expected i.e the organization field shows all organizations listed and gives me an option to pick one. If I implement a model form for Billing it doesn't display all organizations that I can pick from. How to Implement this? I have shared forms.py, views.py code below. models.py class Organization(models.Model): name = models.CharField(max_length=255, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.name) class Billing(models.Model): invoice_name = models.CharField(max_length=50) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) product = models.ManyToManyField(Product) def __str__(self): return str(self.invoice_name) views.py class BillingCreateView(AdminStaffRequiredMixin, SuccessMessageMixin, CreateView): model = Billing form_class = forms.BillingCreateForm template_name = 'dashboard/billing_new.html' success_message = 'Invoice has been created successfully!' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) dashboard/billing_new.html <!-- start form --> <div class="col-lg-12"> <form method="post" action="{% url 'product_create' %}" class="mailform off2" enctype="multipart/form-data"> <div class="row"> {% csrf_token %} <div class="col-md-6 offset-md-3"> {{ form.invoice_name }} </div> <div class="col-md-6 offset-md-3"> {{ form.organization }} </div> <div class="col-md-6 offset-md-3"> {{ form.product }} </div> {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <div class="mfControls col-md-12 offset-md-3 text-left mt-2"> <button type="submit" class="btn white">{% trans "CREATE" %}</button> </div> … -
Django-filter : NameError in custom filtering method
I'm using Django-filter to build a filtering system for my website and I'm having a hard time adapting traditionnal queries inside a custom filtering method of Django-filter. I'm using GeoDjango to retrieve all objects located within a certain distance of a specific location. Here are my models : class UserAdvanced(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) location = models.PointField(blank = True, null = True) class Plat(models.Model): location = models.PointField(blank = True, null = True) As you can see, UserAdvanced and Plat objects have a location attribute and I want to retrieve the Plat objects located near (let's say within 1000m) the UserAdvanced making the request. This can easily be done with : location_user = request.user.useradvanced.location Plat.objects.filter(location__distance_lte=(location_user, D(m=1000))) The problem is that I want to do exactly the same thing within a Filter class from Django-filters with the user being able to choose the distance value. Here is what I have tried : from django.contrib.gis.geos import * from django.contrib.gis.measure import D import django_filters class PlatFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(PlatFilter, self).__init__(*args, **kwargs) distance = django_filters.NumberFilter( field_name='location', method='distance_filter', label='...', widget=forms.NumberInput(attrs={'class': 'form-control'}), ) class Meta: model = Plat def distance_filter(self, queryset, name, value): location_user = self.user.useradvanced.location return queryset.filter(location__distance_lte(location_user, D(m = … -
Try/Except Still throwing RelatedObjectDoesNotExist error? - Django
What's the issue with this try/except block? I am trying to return different pages based on the account type (I have a custom user model) def home(request): if request.user.is_authenticated: try: if CustomUser.objects.get(pk=request.user.id).vendoruser: return redirect('test') except CustomUser.objects.get(pk=request.user.id).vendoruser.DoesNotExist: return redirect('test2') return render(request, 'main/home.html') returns RelatedObjectDoesNotExist at / CustomUser has no vendoruser. Thanks! -
no such table : main.core_answer__old
I tried to create a new Comment based on these models : class Answer(models.Model): answer = models.TextField() author = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name="written_answers") question = models.ForeignKey(Question, on_delete = models.CASCADE, related_name="answers") upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_answers") created_at = models.DateTimeField(auto_now_add = True, blank = True) updated_at = models.DateTimeField(blank = True, null=True) def __str__(self): return str(self.id) class Comment(models.Model): comment = models.CharField(max_length = 200) author = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name = "written_comments") answer = models.ForeignKey(Answer, on_delete = models.CASCADE, related_name="comments") upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_comments") parent_comment = models.ForeignKey("self", on_delete = models.CASCADE, related_name="next_in_thread", null=True, blank=False) created_at = models.DateTimeField(auto_now_add = True, blank = True) updated_at = models.DateTimeField(null=True, blank = True) class Meta: ordering = ('created_at', ) But I get the following error : no such table : main.core_answer__old What did I do wrong? I tried to delete the SQLite table and the migrations and start over, but this error still persists. Please help. -
Exception Value: (Cannot resolve keyword) In Django
I'm about to make a simple webshop, and are currently working on my add to cart button. When I click the add to cart button right now, it returns an error as follows: FieldError at /add-to-cart/box-1/ Exception Value: Cannot resolve keyword 'ordered' into field. Choices are: box, box_id, id, order, quantity, title Related Code views.py: def add_to_cart(request, slug): # Get the item from the slug via get_object_or_404 method box = get_object_or_404(Box, slug=slug) # Check if the user have an order order_box = OrderBox.objects.create(box=box) order_qs = OrderBox.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # Check if order item is in the order if order.box.filter(box__slug=box.slug).exists(): order_box.quantity += 1 order_box.save() else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_box) return redirect('webshop:shop-box', slug=slug) models.py class Order(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderBox) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username I've been searching around, and can find different questions on this topic, however I can't understand what the issue is. I'd much appreciate some help to figure out where I've mistaken, thank you! -
Parse ManyRelatedManager in Django
I have a custom logger that records which user changed which object and shows the differences. I had a problem displaying field differences with a many-to-many relationship(Object of type ManyRelatedManager is not JSON serializable). How I can parse this field??? My intermediate table: class ServiceKey(models.Model): service = models.ForeignKey( Service, on_delete=models.PROTECT, related_name='service', null=False, ) key = models.ForeignKey( ApiKey, on_delete=models.DO_NOTHING, related_name='apikey', null=False, ) class Meta: constraints = [ models.UniqueConstraint(fields=['service', 'key'], name='name of constraint') ] managed = False db_table = '"processing"."service_key"' My model: class Service(models.Model): contractor = models.ForeignKey( Contractor, on_delete=models.CASCADE, related_name='services_contractors', ) amount = models.IntegerField(default=0) callback_url = models.CharField( max_length=128, blank=True, null=True, ) definition = JSONField(null=True, blank=True, default=dict()) name = models.CharField(max_length=255, db_index=True) description = models.TextField(null=True, blank=True) routine = JSONField(null=True, blank=True, default=dict()) service_keys = models.ManyToManyField(ApiKey, through='ServiceKey') @signal_sending(pre_save_with_user, post_save_with_user) def save(self, *args, **kwargs): super(Service, self).save(*args, **kwargs) receiver: @receiver(m2m_changed, sender=ServiceKey) def logger_callback2(sender, **kwargs): action = kwargs['action'] user = None current_request = CrequestMiddleware.get_request() if current_request: user = current_request.user if action == 'pre_add': obj_log = ServiceLog(kwargs['instance'], True) log_record = {'who': str(kwargs.get('user', user)), 'what_model': sender.__name__, 'what_str': str(kwargs['instance']), 'what_id': kwargs['instance'].id, 'is_created': True, 'diff': obj_log.get_diff() } if log_record['diff']: log = Log.objects.create(**log_record) log.save() elif action == 'pre_remove': obj_log = ServiceLog(kwargs['instance'], False) log_record = {'who': str(kwargs.get('user', user)), 'what_model': sender.__name__, 'what_str': str(kwargs['instance']), 'what_id': kwargs['instance'].id, 'is_created': … -
Conditional save() on update?
I having a bit of a straight forward problem. None the less, I am having a hard time solving it. I have one simplified model: class Post(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) creation_date_time = models.DateTimeField(auto_now_add=True) is_published = models.BooleanField(default=False) title = models.CharField(max_length=255, blank=True, null=True) def save(self, *args, **kwargs): if not self.creation_date_time: existing_post = \ self.author.post_set \ .filter( is_published=False, conversation=self.conversation) \ .exists() if existing_post: raise IndexError super().save(*args, **kwargs) Now I want to check that: Every author can only have one non-published (draft) post. The current code checks this on creation of an instance but it gets quite complicated when the instance is updated and not created e. g. via the django admin. It is important, however, that it is possible to update properties on the model regardless of is_published. Only creating two or more posts with is_published=True per user should raise an error. Is there a way to do this that I am not seeing? -
How to show data in popup with server side processing in Django templates (popup)
Here, I have a Django form and view. I am displaying the data from db using datatables in Django template. Now I want the view functionality when, I click on view button it should render corresponding row data in popup boxlike "https://datatables.net/extensions/responsive/examples/display-types/bootstrap4-modal.html" How can we achieve this with Django templates? service.html <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="id_veh" class="control-label"> Car </label> <div class="controls "> {{ervice.veh_id}} </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="id_service_date" class="control-label"> Service Dtae </label> <div class="controls "> {{service.service_date}} </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="id_kms" class="control-label"> Kms </label> <div class="controls "> {{service.kms}} </div> </div> </div> view.py def add_edit_servicing(request, id=None, service=None): # if id: service = Service.objects.get(pk=id) if request.method == 'POST': form = ServiceForm(request.POST, request=request) if form.is_valid(): ...... ..... service.save() context = { 'menu': 'active', 'submenu':'active', 'form': form, 'id':id, 'service':service, } return render(request, 'service.html', context=context) list.html <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-body"> <table id="service" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Veh</th> <th>Service Date</th> <th>KMS</th> <th>View</th> </tr> </thead> </table> </div> </div> </div> </div> </section> {% endblock %} {% block scripts %} <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.bootstrap4.min.js"></script> <script src="https://cdn.datatables.net/select/1.3.0/js/dataTables.select.min.js"></script> <script src="/static/plugins/datatables/dataTables.editor.js"></script> <script src="/static/plugins/datatables/editor.bootstrap4.min.js"></script> <script> $(document).ready(function () { $.extend(true, $.fn.dataTable.defaults, { columnDefs: … -
How to get total pv created for all of User's Django
I have a simple models: class Pv(models.Model): accounts =( ('Sub CF','Sub CF'), ('Special','Special'), ('Directors','Directors'), ('Operations','Operations'), ('LSGDP','LSGDP'), ('DWAP','DWAP'), ('Capacity(USD)','Capacity(USD)') ) acc =( ('Yes','Yes'), ('No', 'No') ) source =( ('GOG','GOG'), ('Others', 'Others') ) pv =( ('General','General'), ('Honorarium','Honorarium') ) center=( ('Cost Center 1','Cost Center 1'), ('Cost Center 2','Cost Center 2'), ('Cost Center 3','Cost Center 3'), ('Cost Center 4','Cost Center 4'), ('Cost Center 5','Cost Center 5') ) stat =( ('Completed','Completed'), ('Returned','Returned'), ('Cancelled','Cancelled') ) IA_System_Code = models.AutoField(primary_key = True) IA_code = models.CharField(max_length = 150) Date_recieved = models.DateField() Pv_reference = models.CharField(unique = True, max_length = 120) Source_of_Funding = models.CharField(max_length=50, choices = source) Cost_center = models.CharField(max_length=50, choices = center) Payee = models.CharField(max_length=500) Description = models.CharField(max_length = 500) Account_code = models.CharField(max_length=350) Gross_amount = models.DecimalField(max_digits=19, decimal_places=2) Withholding_tax = models.DecimalField(max_digits=19, decimal_places=2) Net_amount = models.DecimalField(max_digits=19, decimal_places=2) Status = models.CharField(max_length = 60, choices = stat ) Remarks =models.CharField(max_length = 500, blank = True) Acc_Impress = models.CharField(max_length = 350,choices=acc) Date_returned =models.DateField(null=True,blank = True) Type_of_accounts= models.CharField(max_length = 100, choices = accounts) Type_of_pv = models.CharField(max_length = 20, choices = pv) returned_to_chest = models.DecimalField(max_digits=19, decimal_places=2) created = models.DateTimeField(null=True) created_by = models.ForeignKey('auth.User', blank=True, null=True,\ default=None,on_delete=models.CASCADE,related_name='create') modified = models.DateTimeField(null=True) modified_by = models.ForeignKey('auth.User', blank=True, null=True,\ default=None ,on_delete=models.CASCADE,related_name='modified') class Meta(): ordering = ["IA_System_Code"] def __str__(self): return self.Description def save(self, *args, … -
why I can't get the PasswordResetDoneView page? [django]
when I submit my Email form from PasswordResetView page the email appears via URL as following: http://127.0.0.1:8000/account/password-change/?email=medoabdin%40gmail.com and not directing me to PasswordResetDoneView page and I get no error. how can I show PasswordResetDoneView message page urls.py from django.urls import path from . import views from django.contrib.auth.views import ( LoginView, LogoutView, PasswordResetView, PasswordResetDoneView) from django.urls import reverse_lazy app_name = 'account' urlpatterns = [ # /account/login/ path('login/', LoginView.as_view(template_name='account/login.html'), name='login'), # /account/logout/ path('logout/', LogoutView.as_view(template_name='account/logout.html'), name='logout'), # /account/register/ path('register/', views.register, name='register'), # /account/view-profile/ path('view-profile/', views.view_profile, name='view_profile'), # /account/password-change/ path('password-change/', PasswordResetView.as_view(template_name='account/password_change_view.html', success_url=reverse_lazy('account:password_change_done'), email_template_name='account/reset_password_email.html'), name='password_change'), # /account/password-change/done/ path('password-chane/done/', PasswordResetDoneView.as_view(template_name='account/password_change_done.html'), name='password_change_done'), ] password_change_done.html {% extends 'base.html' %} {% block title %} Success Message {% endblock %} {% block body %} {% if not user.is_authenticated %} <div class="password-change-done"> <div class="container"> <h1 class="text-primary"> The Password Has Been Sent </h1> <p class="lead text-success"> Check your email and following the rest of record until you can go back your own email. </p> <p class="lead text-success"> You need to follow the instructions to get what you want. </p> </div> </div> {% endif %} {% endblock %} password_change_view.html {% extends 'base.html' %} {% block title %} Chnage your Passowrd {% endblock %} {% block body %} {% if not user.is_authenticated %} <div … -
Loan approval emi calculation [closed]
How to calculate emi if loan is approved under django framework using python? Where do we write the code for emi under views.py or under html page? -
Django rq worker process not starting on first deployment to kubernetes
I am running a django_rq instance in kubernetes with a deployment that has a local redis instance inside. I am having trouble getting the worker to actually start. When first deploying the solution with the following settings: - name: rq-worker image: eu.gcr.io/***** volumeMounts: - name: sa-key mountPath: /var/secrets/credentials readOnly: true imagePullPolicy: IfNotPresent resources: requests: cpu: 100m memory: 100Mi command: ["./manage.py"] args: ["rqworker", "*****"] - name: redis image: redis ports: - containerPort: 6379 The worker never starts. I can see this in the django-rq queue. But if i remove the pod and let them recreate the worker is started, with no changes to the deployment. I do not get any logs at all on first deploy. There seems to be something wrong when accessing the process on first deploy, but my kubernetes knowledge doesnt let me fix this. Any ideas would be really appreciated. -
draw multiple text on image with PIL django python
currently its drawing one text on thumbnail and i want to draw multiple watermark on image thumbnail models.py: class Image(models.Model): license_type = ( ('Royalty-Free','Royalty-Free'), ('Rights-Managed','Rights-Managed') ) image_number = models.CharField(default=random_image_number,max_length=12,unique=True) title = models.CharField(default=random_image_number,max_length = 100) image = models.ImageField(upload_to = 'image' , default = 'demo/demo.png') thumbnail = models.ImageField(upload_to='thumbs', blank=True, null=True) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) shoot = models.ForeignKey(ImageShoot, on_delete=models.CASCADE, related_name='Image', null=True,blank=True) image_keyword = models.CharField(max_length=500) description = models.TextField(max_length=3000,null=True,blank=True) credit = models.CharField(max_length=150, null=True,blank=True) location = models.CharField(max_length=100, null=True,blank=True) license_type = models.CharField(max_length=20,choices=license_type, default='') uploaded_at = models.TimeField(auto_now_add=True) def __str__(self): return self.title def save(self, *args, **kwargs): super(Image, self).save(*args, **kwargs) if not self.make_thumbnail(): raise Exception('Could not create thumbnail - is the file type valid?') def make_thumbnail(self): fh = storage.open(self.image.path) base = PILImage.open(fh).convert('RGBA') base.load() width, height = base.size i think this part would go on while loop txt = PILImage.new('RGBA', base.size, (255,255,255,0)) fnt = ImageFont.truetype('arial.ttf', 300) d = ImageDraw.Draw(txt) x = width/3.5 y = height/2.5 d.text((x,y), "liveimages.in", font=fnt, fill=(255,255,255,128)) txt = txt.rotate(45) out = PILImage.alpha_composite(base, txt) out.thumbnail((1000,1000),PILImage.ANTIALIAS) fh.close() thumb_name, thumb_extension = os.path.splitext(self.image.name) thumb_extension = thumb_extension.lower() thumb_filename = thumb_name + '_thumb' + thumb_extension if thumb_extension in ['.jpg', '.jpeg']: FTYPE = 'JPEG' elif thumb_extension == '.gif': FTYPE = 'GIF' elif thumb_extension == '.png': FTYPE = 'PNG' else: return False # Unrecognized … -
Why doesn't Django use select alias when filtering on an annotation?
Am I doing something wrong when filtering on an annotation based on a Subquery? Or why is not the alias used instead of computing the subquery again? Here is a dumb example that showcases my confusion Foo.objects.annotate( progress=Subquery( Job.objects.annotate(ps=Sum('progress')).values('ps')[:1], output_field=IntegerField() ) ).filter(progress__gt=0) currently becomes SELECT "foo"."id", (SELECT SUM(U0."progress") AS "ps" FROM "job" U0 GROUP BY U0."id", U0."progress" LIMIT 1) AS "progress" FROM "foo" WHERE (SELECT SUM(U0."progress") AS "ps" FROM "job" U0 GROUP BY U0."id", U0."progress" LIMIT 1) > 0 instead of simply SELECT "foo"."id", (SELECT SUM(U0."progress") AS "ps" FROM "job" U0 GROUP BY U0."id", U0."progress" LIMIT 1) AS "progress" FROM "foo" WHERE progress > 0 -
Assign Django default model value as count of a foreign field key
I am figuring out how i can add the sum value of fields to a foreign key definition class TestInfo(models.Model): customer_name = models.ForeignKey(TestQuestion, on_delete=models.PROTECT, to_field="correct_answer" default=self.get_count()) def get_count(self): TestQuestion.objects.filter(user=settings.AUTH_USER_MODEL, test_number=TestQuestion.test_number).count(correct_answer=True) -
Django DRF: How to enable activation code for reset password using djoser
I have been successfully able to setup a Django app with Djoser token based authentication. I want to generate a activation code / url and make the user activate through that code / link for account activation or reset password. The Base Endpoints explains how to enable and utilize the activation using the endpoints. But how do I get to create the db models and generate activation code for the users? Am I missing something ? -
Django connecting many products to one user
I'm already a little tired of trying to connect the user profile to the articles he chose from the tables. Namely, if user_1 chooses product_1 and product_2 and user_2 chooses product_1 and product_3, then both users will have assigned to their profiles product_1,2,3,1. How can I solve this I have already tried the relationship "ManyToMany, ForeignKey and OnetoOne", looking for something like OneToMany connection. Models: class UserProd(models.Model): #prod = models.OneToOneField(Products, on_delete=models.SET_NULL, null=True) prod = models.ForeignKey(Products, on_delete=models.SET_NULL, null=True) date = models.TimeField(auto_now_add=True) diet_quantity = models.IntegerField(default=100) unique_number = models.CharField(max_length=10) class Diet(models.Model): profile_user = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) date = models.TimeField(auto_now=True) diet_prod = models.ManyToManyField(UserProd) #diet_prod = models.OneToOneField(UserProd, on_delete=models.SET_NULL, null=True) and my views function: @login_required def add_prod_to_diet(request, pk): user_profile = Profile.objects.get(user = request.user) unique_number = user_profile.pk product = Products.objects.filter(pk = pk).first() user_product, prod_created = UserProd.objects.get_or_create(prod=product, unique_number=unique_number) if not prod_created: user_product.diet_quantity += product.quantity user_product.save() else: user_product.diet_quantity=product.quantity user_product.save() user_diet, diet_created = Diet.objects.get_or_create(profile_user=user_profile) if unique_number == request.user.pk: user_diet.diet_prod.add(user_product) if diet_created: user_diet.unique_number = unique_number user_diet.save() messages.info(request, f"Product {product} has been added to your diet plan.") return HttpResponse(status=204) -
How can I get Javascript onSuccess response object variables in Python?
Background: Working in a Django application, I have a template that performs an action (makes a payement) using an external API. The API call is done in Javascript. On Success, the API returns a response object. This works well on tests. function makePayment(applicationAmount) { let paymentEngine = RmPaymentEngine.init({ key: 'abcd' firstName: '{{ user.f_name }}', onSuccess: function(response) { console.log('callback Successful Response', response); // TODO: Add a function to post the payment records to the database // response from the API contains a dictionary like (read json) object // how can I get that response object in Python and use those response // object values to update a django model database records }, onError: function(response) { console.log('callback Error Response', response); // TODO: Add a function to throw an error message }, onClose: function() { console.log("closed"); } }); } Question: How can I get that onSuccess response object variables in Python and use those response object values to update a django model database records? Looked at this link: How do I return the response from an asynchronous call? but can't seem to implement my need. I'd be happy to be directed to a simple resource that explains the procedure, not something very involved … -
ErrorDetail(string='Expected a list of items but got type "ReturnDict".', code='not_a_list')
When I test ThankYouMessage I get error {'images': {'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "ReturnDict".', code='not_a_list')]}} tests class ThankYouMessagesSerializerTestCase(MediaTestCase, TestCase): def setUp(self) -> None: self.thank_you_message = ThankYouMessageFactory() self.thank_you_image = ThankYouImageFactory() def test_thank_you_message_deserialize(self) -> None: image_data = ThankYouMessageImageSerializer(self.thank_you_image).data thank_you_data = ({'text': 'Some text', 'images': image_data}) serializer = ThankYouMessagesSerializer(data=thank_you_data) serializer.is_valid() print(serializer.errors) # {'images': {'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "ReturnDict".', code='not_a_list')]}} self.assertTrue(serializer.is_valid()) models class ThankYouMessage(models.Model): donation = models.ForeignKey("donation.Donation", on_delete=models.CASCADE, related_name='thank_message', unique=True) text = models.TextField() class ThankImage(models.Model): message = models.ForeignKey("donation.ThankYouMessage", on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to="thankmessageimages/") factories class ThankYouMessageFactory(factory.django.DjangoModelFactory): class Meta: model = ThankYouMessage donation = factory.SubFactory(DonationFactory) text = factory.Sequence(lambda n: f"Thank you {n}") When I test При тестировании сериализатора получаю ошибку class ThankYouImageFactory(factory.django.DjangoModelFactory): class Meta: model = ThankImage image = factory.django.ImageField(name=f"testimage.jpeg", color="blue") message = factory.SubFactory(ThankYouMessageFactory) serializers class ThankYouMessageImageSerializer(ModelSerializer): class Meta: model = ThankImage fields = '__all__' read_only_fields = ("message", "id") class ThankYouMessagesSerializer(ModelSerializer): images = ThankYouMessageImageSerializer(many=True) donation = serializers.CharField(source='donation.id', read_only=True) donor_id = serializers.CharField(source='donation.donor.id', read_only=True) class Meta: model = ThankYouMessage fields = 'text', 'donation', 'donor_id', 'images' If I write image_data = ThankYouMessageImageSerializer(self.thank_you_image, many=True).data I get TypeError: 'ThankImage' object is not iterable -
grabbing data by ajax calling from django rest api?
i want to grab my data from the rest api by ajax in the homepage. But the ajax calling isn't working . I'm not getting any data. my blog api serializers view: from rest_framework import serializers from accounts.api.serializers import UserDisplaySerializer from blog.models import post class postModelSerializer(serializers.ModelSerializer): author = UserDisplaySerializer() class Meta: model = post fields = [ 'author', 'content' ] my blog api urls: from django.urls import path, re_path from .views import postListAPIView from . import views urlpatterns = [ path('', postListAPIView.as_view(), name='blog-home'), #api/blog mysite api urls for blog: 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 blog import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('blog.urls')), path('api/', include('blog.api.urls')), ] my main home.html template: {% extends "blog/base.html" %} <style> #post-container{ } </style> {% block script %} <script type="text/javascript"> $(document).ready(function(){ console.log("working") $.ajax({ url: "/api/", method: "GET", sucess: function(data){ console.log(data) }, error: function(data){ console.log("error") console.log(data) } }) }); </script> {% endblock script %} {% block content %} <div id='post-container'> </div> <article class="content-section"> <div class="post-bar"> <a href="" class="mdl-button mdl-js-button mdl-button--fab"> <i class="material-icons">add</i> </a> <p class="text">Tab the button for write a post</p> </div> <div … -
Including DJANGO_SETTINGS_MODULE in environment variable
Please,how do I include DJANGO_SETTINGS_MODULE in my environment variable so that I won't be using cd myproject before I could run any command in the terminal; below is my setting in the environment variable. C:\Users\Freddy\AppData\Local\Programs\Python\Python38-32;C:\Users\Freddy\AppData\Local\Programs\Python\Python38-32\Scripts -
How to solve error in sql decode of annotation in django
I am working on django framework with mangodb database. CRUD operations are working fine but I am facing an issue on annotation query but receiving error: djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT "app_message"."type", SUM(CASE WHEN "app_message"."type" = %(0)s THEN %(1)s ELSE %(2)s END) AS "bot" FROM "app_message" GROUP BY "app_ message"."type" LIMIT 21 Params: ('Outbound', 1, 0) Version: 1.2.38 Tried version 1.2.31 as well but no luck. python version: 3.6.1 Django version: 2.2.7