Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert Date model field with filter query
i'm baffled by this one and no amount of google has come up with an answer. I'm running this query against my database: pedigrees = Pedigree.objects.filter(account=attached_service, status='alive').values('reg_no', 'parent_father__reg_no', 'parent_mother__reg_no', 'sex', 'breed__breed_name', 'dob', 'status') I'm using values to limit the amount of data that comes back. As you can see one of the columns i need is the dob. however the return i'm getting in the field is {'dob': datetime.date(2019, 9, 24)}, which isn't ideal. I'd like to change it's value to "YYYY-mm-dd". I've tried using the DATE_FORMAT setting in settings.py and i've tried lots of other methods suggested on here but nothing has worked. Model item looks like this... dob = models.DateField(blank=True, null=True, verbose_name='date of birth', help_text="Date formats: 1984/09/31, 84/09/31, 31/09/1984, 31/09/84, 1984-09-31, 84-09-31, 31-09-1984, 31-09-84") The data that's being extracted is being sent to an API, i've also built the API so i could change it's format at the other end but i'd rather not. -
Counting problem in django blog: using django ajax
I created a like button for my django blog using ajax but I'm getting an error that its not counting properly, at first its 0 like in a post when i hit like it works 1 like appeared with unlike button but when i hit unlike and like again it gives 2 likes and sometimes when i unlike it show -1 like i think its jQuery problem I'm not an expert in jQuery jQuery $(document).ready(function() { function updateText(btn, newCount, verb) { btn.text(newCount + " " + verb) } $(".like-btn").click(function(e) { e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) |0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, addLike, "Unlike") } else { updateText(this_, removeLike, "Like") // remove one like } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) post.html {% if user not in post.likes.all %} <p><a class='like-btn' data-href='{{ object.get_api_like_url }}' data-likes='{{ object.likes.all.count }}' href='{{ object.get_like_url }}'> {{ object.likes.all.count }} Like</a></p> {% else %} <p><a class='like-btn' data-href='{{ object.get_api_like_url }}' data-likes='{{ object.likes.all.count }}' href='{{ object.get_like_url }}'> {{ object.likes.all.count }} Unlike</a></p> {% endif %} … -
Django query database and adding users to specific group of objects
I a trying to query my Blog model such that it will return the number of likes for a blog post with the title = example and name = something class Post(models.Model): title = models.CharField(max_length=20) name = models.CharField(max_length=100) content = models.CharField(max_length=100) likes = models.ManyToManyField(User, blank=True, related_name='likes') right now I am trying to get the count of likes in my model with this method: def average_voting(self): likes = Post.objects.filter(title=self.title,name=self.name).likes.count() return likes and for adding a user I am using: Post.objects.filter(title="example",name="something").likes.add(User) but my lines are not working I cannot figure out what I'm doing wrong. -
How to create a Barcode code using python and store the png file in s3 without saving in local
import barcode from barcode.writer import ImageWriter from io import StringIO # python3; python2: BytesIO import boto3 import pandas as pd def generate_asst(request): df=pd.DataFrame list_of_images = [] for i in range(10): number = 'xxx43256' number = number + str(i) print(number) EAN = barcode.get_barcode_class('Code39') ean = EAN(number, writer=ImageWriter()) fullname = str(i) + 'barcodhhe' filename = ean.save(fullname) filename = ean.save(fo) with open(filename, 'rb') as f: contents = f.read() fo.close() s3 = boto3.resource('s3') s3_obj = s3.Object(bucket_name='bucket-name', key=fullname).put(Body=contents) s3_client = boto3.client('s3') response = s3_client.generate_presigned_url('get_object', Params={'Bucket': 'bucket-name', 'Key': fullname},ExpiresIn=300 ) list_of_images.append({"imagepath":response}) print(response) df=pd.DataFrame(list_of_images) df=json.loads(df.to_json(orient='records')) print(df) # return fullname return JsonResponse(df,safe=False) -
Heroku + Django + Redis Cloud: Connect call failed
I have a django project on heroku. I add Redis Cloud to make my Channels Layers. When I visit the page with my WebSocket I don't see the response and I have this errors in Heroku LOG: Exception inside application: [Errno 111] Connect call failed ('127.0.0.1', 6379) raise OSError(err, 'Connect call failed %s' % (address,)) ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 6379) ERROR Task exception was never retrieved DEBUG WebSocket closed for ['10.32.185.71', 22959] ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 6379) DEBUG Parsed Redis URI ('localhost', 6379) DEBUG Creating tcp connection to ('localhost', 6379) DEBUG WebSocket ['10.38.200.97', 14816] open and established 10.38.200.97:14816 - - [04/May/2020:15:34:35] "WSCONNECT /ws/channel/" - - DEBUG WebSocket ['10.38.200.97', 14816] accepted by application DEBUG Parsed Redis URI ('localhost', 6379) DEBUG Creating tcp connection to ('localhost', 6379) DEBUG Parsed Redis URI ('localhost', 6379) DEBUG Creating tcp connection to ('localhost', 6379) DEBUG WebSocket incoming frame on ['10.38.200.97', 14816] ERROR Exception inside application: [Errno 111] Connect call failed ('127.0.0.1', 6379) My CACHES configuration (from https://devcenter.heroku.com/articles/rediscloud#configuring-redis-on-django): redis_url = urlparse.urlparse(os.environ.get('REDISCLOUD_URL')) CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), 'OPTIONS': { 'PASSWORD': redis_url.password, 'DB': 0, } } } And my CHANNEL_LAYERS: CHANNEL_LAYERS = { "default": { 'BACKEND': … -
A Django powered backend with PostgreSQL or Firebase backend
I’m a backend developer and I love using Django and PostgreSQL for backends on a Linux server. But I’ve been learning flutter and I’m convenient with it and was reading about firebase real time. I just want to know if firebase offers more functionality than building my own backend. I prefer to build my own backend but I have been reading that firebase offers real time which Postgres doesn’t, I don’t really understand this and doesn’t it really count? Thank you. -
JSON serializable Problem in Django When Try to Use Session
I try to add a cart process in my ecommerce prject which is built with Python Django Framework. But when i try to check data the visitor is authenticated or not and try to return data from model manager I face a json serializable problem. In Bellow i give you the sample code, Here is my view file: from django.shortcuts import render from .models import Cart from django.core import serializers # Create your views here. def cart_create(user=None): cart_obj = Cart.objects.create(user=None) print('New Cart Created') return cart_obj def cart_home(request): cart_id = request.session.get("cart_id", None) qs = Cart.objects.filter(id=cart_id) if qs.count() == 1: print("Cart Id exists") cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: #cart_obj = cart_create() cart_obj = Cart.objects.new(user=request.user) request.session['cart_id'] = cart_obj return render(request, "carts/home.html") Here Is my Model File: from django.db import models from django.conf import settings from products.models import Product from django.core.serializers import serialize User = settings.AUTH_USER_MODEL # Create your models here. class CartManager(models.Manager): def new(self, user=None): print(user) user_obj = None if user is not None: if user.is_authenticated: user_obj = user return self.model.objects.create(user=user) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) … -
django download file not found
I'm using Python 3.6 and django 2.2 to develop a webserver. I want to have a webpage displaying a download link for a file I generated based on user input. In my setting.py I have: MEDIA_ROOT = os.path.join.(BASE_DIR,'media') MEDIA_URL='/media/' In my views.py I have query.outputfile.name = os.path.join('submission',query_id,'output_file.txt') to associate the filefield object to the file that I created: path/to/project/media/submission/[query_id]/output_file.txt And when I include print(query.outputfile.url) I got: media/submission/[query_id]/output_file.txt In my html template I have <a href={{ query.outputfile.url }} download> Download output file here </a> On the webpage the file link points to [local ip]/media/submission/[query_id]/output_file.txt But when I click on the link chrome says "Failed - No file" and on the cmd line I got Not Found: /media/submission/[query_id]/output_file.txt I found related questions like this one but do not understand what's wrong with my code. My questions are: The .url seems to be relative to my MEDIA_ROOT, but why it cannot find my file? Does the cmd line error point to the absolute path /media/... ? I tried to make that path and file but still got the same error. What should I do to generate the download link? Thanks -
Is there a way of a inserting blank datetimefield from another table?
class Customer(models.Model): last_purchase = models.DateTimeField(blank=True, null=True) I have a blank DateTimeField, which will continuously update itself with the last modified DateTimeField in the corresponding table. class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) How will this look on views? -
no such table: main.auth_user__old (OperationalError)
Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/main/tutorial/add/ Django Version: 2.1.4 Python Version: 3.8.2 Traceback: File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py" in execute 296. return Database.Cursor.execute(self, query, params) The above exception (no such table: main.auth_user__old) was the direct cause of the following exception: File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in wrapper 604. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in add_view 1637. return self.changeform_view(request, None, form_url, extra_context) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in changeform_view 1525. return self._changeform_view(request, object_id, form_url, extra_context) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in _changeform_view 1568. self.log_addition(request, new_object, change_message) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in log_addition 804. return LogEntry.objects.log_action( File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/models.py" in log_action 29. return self.model.objects.create( File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/query.py" in create 413. obj.save(force_insert=True, using=self.db) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/base.py" in save 717. self.save_base(using=using, force_insert=force_insert, File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/base.py" in save_base 748. updated = … -
How can I display images in Django after uploading?
I'm making a small blog. And I will be creating a cover image uploading system. But after uploading, I'm unable to retrieve the image. Do you have any solutions? Here's my model.py: class Post(models.Model): id = models.AutoField author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content_images = models.ImageField(default="media/noimg-l.jpg") and here's form.py: class Createcontent(forms.ModelForm): class Meta: model = Post fields = ( "title", "content", "slug", "content_images", "status", ) file = forms.FileField() widgets = { "content": SummernoteWidget(), } and this is the HTML I'm using: <div class="row"> <form method="POST" enctype="multipart/form-data" class="post-form">{% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> and my setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 -
Django... Why template page doesn't show results of the query in the view function
Sorry I am new to django and I made mistake or bunch of mistakes somewhere and I don't see what is wrong... Django also doesn't let me know where is the mistake... If somebody pinpoint me to the answer or let me know what is wrong that would be totally awesome... Thank you I have 2 models: one is the Director (pk = director_name) and one is the Worker (pk = worker_name)... Means family names, unique... They are many to many connection for the database. One worker can be under 2 supervisors... So, another model is Connection (fk = director_connect, fk = worker_connect, pk = (director_connect, worker_connect))... By the way, in postgresql the database model as I just described, but when I run "inspectdb" in cmd... it gives me: worker_connect = models.OneToOneField(...)// I made this connection by the alphabet, but somehow for Django, instead of ForeignKey it is OneToOneField? Can I just change it to models.ForeignKey(...)? And then apply changes? director_connect = models.ForeignKey(...) // as expected... def __str__(self): return f'{self.worker_connect}' def get_absolute_url(self): return reverse('director-detail', args=[str(self.director_connect)]) class Meta: managed=False db_table 'Connection' unique_together = (('director_connect', 'worker_connect')) ...So, the idea is to be able to find which worker under whose supervision, and whom … -
Is there a way to crop an image using only css? [duplicate]
I am currently working on a django project which is a youtube clone.I scrape the image of the thumbnails of the videos.When I do so, I faced a problem in fixing the image in the card(from materializecss).The image has empty black space on top and bottom.This is URL of a sample image:https://i.ytimg.com/vi/bt4-FwVe1Fk/hqdefault.jpg Now i want to crop the image so that, the empty black space doesn't show up.Is there a way to do it with only CSS?Any help would be appreciated. Thank You in advance. -
How to post multiple objects in Django Rest API from HTML form where multiple input filed id are same
Here You Can See My form where user Can give input and my goal is to take all the data user-provided and post it through API Firstly I want to see you my HTML code : <div class="content" id="skills"> <form action="#" method="post" class="job-post-form ajax" id="skill_create"> <div class="form-group row"> <label class="col-sm-3 col-form-label">Type Skills</label> <div class="col-sm-9"> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text">01</div> </div> <select class="form-control" data-text="name" id="skill_name_id" data-value="id" data-placeholder="Skills" data-src="/api/skill_list"> </select> <input type="number" id="rating" class="form-control" placeholder="Rating"> <label class="form-control" >Verified By SkillCheck</label> <input type="checkbox" id="verified_by_skillcheck" style="margin-top:16px;" name="Skillcheck" value="X"> </div> </div> </div> <div class="form-group row"> <div class="offset-sm-3 col-sm-9"> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text" >02</div> </div> <!-- <input type="text" class="form-control" >--> <select class="form-control" id="skill_name_id" data-text="name" data-value="id" data-placeholder="Skills" data-src="/api/skill_list"> </select> <input type="number" id="rating" class="form-control" placeholder="Rating"> <label class="form-control">Verified By SkillCheck</label> <input type="checkbox" id="verified_by_skillcheck" style="margin-top:16px;" name="Skillcheck" value="X"> </div> </div> </div> And now I will show you my script code : function skillGet(){ var skill_id = $("#skill_name_id").val(); var skill_rating = $("#rating").val(); var isVerified = $('input[name="Skillcheck"]:checked').val(); var path = window.location.pathname.split('/'); var id = path[path.length-2]; if (!isVerified){ isVerified = "False"; } else{ isVerified = "True"; } var data = { "professional_id" : id, "skill_name_id": skill_id, "rating": skill_rating, "verified_by_skillcheck": isVerified } skillCreateUrl = "/api/professional/professional_skill/"; if(Object.keys(data).length>1){ post(skillCreateUrl, JSON.stringify(data)); } } By this … -
How to get intermediary models instances related to a specific model in a Django symmetrical m2m relation?
Since Django 3.0, setting symmetrical=True for recursive m2m relationships using a through model is supported. [docs] For exemple, with the following models, where Town objects are symmetricaly linked together through Roads objects : class Town(models.Model): neighboors = models.ManyToManyField('self', through='Road', symetrical=True) class Road(models.Model): from_town = models.ForeignKey('Town', models.CASCADE, related_name='road_from') to_town = models.ForeignKey('Town', models.CASCADE, related_name='road_to') How to get all Road instances related to a specific town? As the doc explains, related_name of the two fk in the Road models have to be different, meaning a single reverse acessor like town.related_road will not work. Of course, I can set two different related_name and join the results of two queries, but that does not seems very Pythonic to me: class Town(models.Model): ... @property def roads(self): return self.road_to + self.road_from Is there any other way I can achieve this ? -
Why does Django create a new instance instead of update?
I want to modify some of my 'Location' object with an UpdateView. class LocationUpdateView(UpdateView): #form_class = LocationForm model = LocationTemplate fields = ['address','district','grid_x','grid_y'] #template_name = 'locationTemplate_update_form' def get_success_url(self): return reverse('location_detail', kwargs={'pk': self.object.pk}) def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): self.object = self.get_object() for loc in Location.objects.all(): if self.object.location_name == loc.location_name: setattr(loc,'address',(form.cleaned_data['address'])) setattr(loc,'district',(form.cleaned_data['district'])) setattr(loc,'grid_x',(form.cleaned_data['grid_x'])) setattr(loc,'grid_y',(form.cleaned_data['grid_y'])) loc.save() return self.form_valid(form) else: return self.form_invalid(form) However, instead of updating the objects, the above loop creates a new object with the update information(except the location_name is None). I was expecting setattr() to modify the attributes of that specific loc instead of creating new instances. models.py class LocationTemplate(models.Model): location_name = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=300, null=True, blank=True) district = models.CharField(max_length=300, null=True, blank=True) grid_x = models.IntegerField(null=True, blank=True) grid_y = models.IntegerField(null=True, blank=True) def __str__(self): return self.location_name + ", Address: " + self.address + ", District: " + self.district + ", Coordinates: (" + str(self.grid_x) + ", " + str(self.grid_y) + ")" forms.py class LocationForm(forms.ModelForm): class Meta: model = LocationTemplate #exclude = ('patient',) fields=['location_name', 'address','district', 'grid_x','grid_y'] -
Rename files uploaded in Django admin and omit fields in the form
I'm using Django 3.0.5 and I want to upload images in the Django admin. I'm trying to: 1) change the filename uploaded the media folder based on the image data. 2) Omit fields in the displayed form because these are auto generated. The model is registered in admin.py This is my code in models.py: from django.db import models from hashlib import md5 from PIL import Image from io import BytesIO class NewImage(models.Model): image_name = models.CharField(max_length=255, default='') pub_date = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to='images/') height = models.IntegerField(default=0) width = models.IntegerField(default=0) extension = models.CharField(max_length=20, null=False, default='') image_hash = models.CharField(max_length=50, null=False, unique=True, db_column='hash', default='') def __str__(self): return self.image_name @staticmethod def hash_exists(hash): return NewImage.objects.filter(image_hash=hash).exists() def generate_name(self): try: img_id = NewImage.objects.values('id').order_by('-id').first()['id'] + 1 except: img_id = 1 self.image_name = "%s_%s" % (img_id, self.image_hash[-4:]) def save(self, *args, **kwargs): img = Image.open(self.image) self.image_hash = md5(img.tobytes()).hexdigest() if not self.pk: try: if self.hash_exists(self.image_hash): raise ValueError("image hash already exists, duplicate image!") except ValueError as err: print(err.args) return "" self.width, self.height = img.size self.extension = img.format.lower() self.generate_name() super(NewImage, self).save(*args, **kwargs) 1) How can I have the file in the media folder be image_name 2) For omitting the fields. Based on SOF answers, I tried the following (it doesn't work) in forms.py: from … -
Why do i have this error message while migrating on django
Here's my models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField (max_lenght=2083) Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\core\management\__init__.p y", line 401, in execute_from_command_line utility.execute() File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\core\management\__init__.p y", line 377, in execute django.setup() File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\apps\registry.py", line 11 4, in populate app_config.import_models() File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\dill\AppData\Local\Programs\Python\Python37\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 680, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\dill\PycharmProjects\PyShop\products\models.py", line 3, in class Product(models.Model): File "C:\Users\dill\PycharmProjects\PyShop\products\models.py", line 7, in Product image_url = models.CharField (max_lenght=2083) File "C:\Users\dill\PycharmProjects\PyShop\venv\lib\site-packages\django\db\models\fields__init__. py", line 984, in init super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'max_lenght' -
Accessing model attributes in Django
I'm trying to show users the product variations that they have selected. While the code is working and saving the variation in the database, I am not being able to show them on my html page. Only : is being rendered. If I try {{ order_item.variation.all }} and it gives an empty queryset like : <QuerySet []>. And if I try {{ order_item.variation }}, it says : products.Variation.None. What is the problem? Is the way I'm calling it wrong? This is what I've tried: My models.py: class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, blank=True) variation_type = models.CharField(max_length=120, choices=VAR_TYPES, default='Size') title = models.CharField(max_length=120, null=True, blank=True) price = models.FloatField(null=True, blank=True) is_available = models.BooleanField(default=True) objects = VariationManager() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) variation = models.ManyToManyField(Variation) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20) ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) variation = models.ManyToManyField(Variation) My order_summary.html: {% for order_item in object.items.all %} <tbody> <tr> <th scope="row" class="border-0"> <div class="p-2"> <img src="{{ order_item.item.image_url }}" alt="" width="70" class="img-fluid rounded shadow-sm"> <div class="ml-3 d-inline-block align-middle"> <h5 class="mb-0"> <a href="{{ order_item.item.get_absolute_url }}" class="text-dark d-inline-block align-middle">{{ order_item.item.title }}</a> {% if order_item.variation %} <ul> <h6>{{ order_item.variation.variation_type }} : {{ … -
Django M2M how to set default reference in models
after User has been created I want User get default products by id, I must use def save(): func in models but dont know how to do it My models: class Product(models.Model): user = models.ManyToManyField(get_user_model() , blank=True) class User(AbstractBaseUser): first_name = models.CharField(max_length=254) -
Can I fully integrate Wagtail CMS with an Angular frontend?
So I was needing some kinda of CMS for my project and how I have experience with Django I was thinking of using Wagtail CMS. For example, let's say I'm doing some kinda of blog with Angular 9 as frontend, with user sign up, comments, contact forms and all that stuff. I was reading the Wagtail documentation and the "read_only" API had me worried, my question is simple: Can I fully integrate Wagtail CMS with an Angular frontend? With all the functionalities, because if I was using an API I would need POST, PATCH, etc... -
Sonar Cloud Security Hotspot for Django manage.py file
Sonar Analysis gives the following Security HotSpot in the manage.py file of my Django Project "Make sure that command line arguments are used safely here" On the following line execute_from_command_line(sys.argv) On the argv to be precise Any idea how I can fix this? -
How do i make a functioning Delete confirmation popup in Django using Bootstrap4 Modal
My views.py file looks like this. def deleteOrder(request, pk): order = Order.objects.get(id=pk) if request.method=="POST": order.delete() return redirect('/') context = {"item":order} return render(request, 'accounts/delete.html', context) My url.py file looks like this. urlpatterns = [ path('delete_order/<str:pk>', views.deleteOrder, name="delete_order"), ] Bootstrap Delete Popup i want to apply <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> My Home page which contain deleting row data for a table looks like this. <table class="table table-sm"> <tr> <th>Product</th> <th>Date Ordered</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for order in orders %} <tr> <td>{{ order.product }}</td> <td>{{ order.date_created }}</td> <td>{{ order.status }}</td> <td><a class="btn btn-sm btn-info" href="{% url 'update_order' order.id %}">Update</a></td> **<td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Delete</a></td>** </tr> {% endfor %} </table> The Line that i have added ** asterisks(intentionally) is the one i want to modify so that when i click on Delete button, a Bootstrap popup … -
How to pass django serializers Validation Error of a field to React as json fromat
In my rest framework user registration form I successfully created a custom registration form and added some validators. It shows corresponding validation errors in rest framework.but when linked this to react through redux it gets the error but not showing corresponding validation errors like " A user is already registered with this e-mail address. ". The rest showsit like this. JSON format that gets at react is this error: { message: 'Request failed with status code 400', name: 'Error', fileName: 'http://localhost:3000/static/js/1.chunk.js', lineNumber: 871, columnNumber: 15, stack: 'createError@http://localhost:3000/static/js/1.chunk.js:871:15\nsettle@http://localhost:3000/static/js/1.chunk.js:1092:12\nhandleLoad@http://localhost:3000/static/js/1.chunk.js:346:13\nEventHandlerNonNull*dispatchXhrRequest@http://localhost:3000/static/js/1.chunk.js:322:5\nxhrAdapter@http://localhost:3000/static/js/1.chunk.js:301:10\ndispatchRequest@http://localhost:3000/static/js/1.chunk.js:924:10\npromise callback*request@http://localhost:3000/static/js/1.chunk.js:712:23\nforEachMethodWithData/Axios.prototype[method]@http://localhost:3000/static/js/1.chunk.js:736:17\nwrap@http://localhost:3000/static/js/1.chunk.js:1252:15\nsignUp/<@http://localhost:3000/static/js/main.chunk.js:3406:50\ncreateThunkMiddleware/</</<@http://localhost:3000/static/js/1.chunk.js:40096:18\ndispatch@http://localhost:3000/register:1:28546\nonAuth@http://localhost:3000/static/js/main.chunk.js:3305:110\nRegMain/this.handlesubmit@http://localhost:3000/static/js/main.chunk.js:2684:62\ncallCallback@http://localhost:3000/static/js/1.chunk.js:8030:18\ninvokeGuardedCallbackDev@http://localhost:3000/static/js/1.chunk.js:8079:20\ninvokeGuardedCallback@http://localhost:3000/static/js/1.chunk.js:8132:35\ninvokeGuardedCallbackAndCatchFirstError@http://localhost:3000/static/js/1.chunk.js:8147:29\nexecuteDispatch@http://localhost:3000/static/js/1.chunk.js:8232:46\nexecuteDispatchesInOrder@http://localhost:3000/static/js/1.chunk.js:8257:24\nexecuteDispatchesAndRelease@http://localhost:3000/static/js/1.chunk.js:11141:33\nexecuteDispatchesAndReleaseTopLevel@http://localhost:3000/static/js/1.chunk.js:11150:14\nforEachAccumulated@http://localhost:3000/static/js/1.chunk.js:11122:12\nrunEventsInBatch@http://localhost:3000/static/js/1.chunk.js:11167:25\nrunExtractedPluginEventsInBatch@http://localhost:3000/static/js/1.chunk.js:11377:23\nhandleTopLevel@http://localhost:3000/static/js/1.chunk.js:11421:40\nbatchedEventUpdates$1@http://localhost:3000/static/js/1.chunk.js:29567:16\nbatchedEventUpdates@http://localhost:3000/static/js/1.chunk.js:8639:16\ndispatchEventForLegacyPluginEventSystem@http://localhost:3000/static/js/1.chunk.js:11431:28\nattemptToDispatchEvent@http://localhost:3000/static/js/1.chunk.js:12151:48\ndispatchEvent@http://localhost:3000/static/js/1.chunk.js:12072:45\nunstable_runWithPriority@http://localhost:3000/static/js/1.chunk.js:41893:16\nrunWithPriority$1@http://localhost:3000/static/js/1.chunk.js:18917:14\ndiscreteUpdates$1@http://localhost:3000/static/js/1.chunk.js:29584:16\ndiscreteUpdates@http://localhost:3000/static/js/1.chunk.js:8652:16\ndispatchDiscreteEvent@http://localhost:3000/static/js/1.chunk.js:12051:22\nEventListener.handleEvent*addEventBubbleListener@http://localhost:3000/static/js/1.chunk.js:11905:15\ntrapEventForPluginEventSystem@http://localhost:3000/static/js/1.chunk.js:12045:31\ntrapBubbledEvent@http://localhost:3000/static/js/1.chunk.js:12015:36\nsetInitialProperties@http://localhost:3000/static/js/1.chunk.js:13826:27\nfinalizeInitialChildren@http://localhost:3000/static/js/1.chunk.js:15351:27\ncompleteWork@http://localhost:3000/static/js/1.chunk.js:26705:44\ncompleteUnitOfWork@http://localhost:3000/static/js/1.chunk.js:29895:20\nperformUnitOfWork@http://localhost:3000/static/js/1.chunk.js:29868:16\nworkLoopSync@http://localhost:3000/static/js/1.chunk.js:29833:26\nperformSyncWorkOnRoot@http://localhost:3000/static/js/1.chunk.js:29451:13\nscheduleUpdateOnFiber@http://localhost:3000/static/js/1.chunk.js:28883:32\nupdateContainer@http://localhost:3000/static/js/1.chunk.js:32032:19\nlegacyRenderSubtreeIntoContainer/<@http://localhost:3000/static/js/1.chunk.js:32415:26\nunbatchedUpdates@http://localhost:3000/static/js/1.chunk.js:29601:16\nlegacyRenderSubtreeIntoContainer@http://localhost:3000/static/js/1.chunk.js:32414:25\nrender@http://localhost:3000/static/js/1.chunk.js:32497:14\n./src/index.js@http://localhost:3000/static/js/main.chunk.js:4166:50\n__webpack_require__@http://localhost:3000/static/js/bundle.js:785:30\nfn@http://localhost:3000/static/js/bundle.js:151:20\n1@http://localhost:3000/static/js/main.chunk.js:4181:18\n__webpack_require__@http://localhost:3000/static/js/bundle.js:785:30\ncheckDeferredModules@http://localhost:3000/static/js/bundle.js:46:23\nwebpackJsonpCallback@http://localhost:3000/static/js/bundle.js:33:19\n@http://localhost:3000/static/js/main.chunk.js:1:71\n', config: { url: 'http://127.0.0.1:8000/rest-auth/register/', method: 'post', data: '{"fname":"Abhiram","lname":"PS","username":"rooteeee","phone":"8589967868","email":"abhirampjayan@outlook.com","cemail":"abhirampjayan@outlook.com","password1":"abhi1998","password2":"abhi1998","gender":"M","acctype":"Student"}', headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json;charset=utf-8' }, transformRequest: [ null ], transformResponse: [ null ], timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1 } } source code of serializer.py is given bellow from rest_framework import serializers from accounts.models import Account from allauth.account import app_settings as allauth_settings from allauth.utils import email_address_exists from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email from rest_framework.validators import UniqueValidator from rest_framework.response import Response from rest_framework import status class CustomUserDetailsSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('pk','email','fname','lname','username','phone','gender','acctype') #read_only_fields = ('email','acctype','fname','lname') class CustomRegisterSerializer(serializers.Serializer): fname = serializers.CharField(required=True, write_only=True) lname = serializers.CharField(required=True, write_only=True) username = serializers.CharField(min_length=allauth_settings.USERNAME_MIN_LENGTH,required=allauth_settings.USERNAME_REQUIRED,validators=[UniqueValidator(queryset=Account.objects.all(),message='A user is already registered with this … -
pytest-django: users created with create_user are always authenticated
I'm trying to write a fixture to generate Django users from custom user model. The weird thing is that the newly created user results authenticated by default, while I expect it to be anonymous. What am I doing wrong? Fixture: import pytest @pytest.fixture def create_user(db, django_user_model): def make_user(**kwargs): return django_user_model.objects.create_user(**kwargs) return make_user Test the fixture: @pytest.mark.django_db def test_fixture_create_user(create_user): user = create_user(user={'email': 'foo@bar.com', 'password': 'bar'}) assert user.is_authenticated is True # <-- this should be False but it's True assert user.is_anonymous is True # <-- this fails The test fails this way: E assert False is True E + where False = <CustomUser: foo@bar.com>.is_anonymous