Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HOW RO CODIFY IN VIEWS USING DJANGO CODE, AS I WANT TO PREVENT THE FURTHER UPDATE ALL ROW FIELDS OF POSTGRESQL TABLE BASED , IF ONE FIELD IS UPDATED
HERE IS MY MODELS CODE ''' `class defectrecord(models.Model): # id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date=models.DateTimeField() natureofwork=models.CharField(max_length=100, null= True, blank=True) element=models.CharField(max_length=100, null= True, blank=True) defectobserved=models.CharField(max_length=500) repemployee=models.CharField(max_length=100) appemployee=models.CharField(max_length=100, blank=True) defappempremark=models.CharField(max_length=500, blank=True) defallocemp=models.CharField(max_length=100, blank=True) rectdetail=models.CharField(max_length=500, blank=True) rectdate=models.DateTimeField(null=True,blank=True) permit=models.BigIntegerField(null=True,blank=True) workcarried=models.CharField(max_length=500, blank=True) rectemployee=models.CharField(max_length=100, blank=True) rectappemployee=models.CharField(max_length=100, blank=True) rectappempremark=models.CharField(max_length=500, blank=True) image=models.ImageField(max_length=100, null= True, blank=True) class Meta: get_latest_by='id' ''' IF LAST 'OBJECT FIELD 'rectappempremark' IS UPDATED THEN SOME CODE IN VIEWS.PY TO PREVENT FURTHER UPDATE OF ALL MODELS FIELDS OF THAT PARTICULAR ROW (IDENTIFIED BY id). Above model contains save function and update functions based on permission code in views.py -
use for loop with JavaScript template literal function
I have a web app, frontend using normal HTML5, backend using Django. In the frontend page, I have a JavaScript template literal function. Which is supposed to render all the individual value into a selection box of a queryset passed from backend to a bootstrap table. view.py: def view_material(request): query_results_publisher = Publisher.objects.all() return render(request, 'material/index.html', context={'Publisher':query_results_publisher}) index.html(bootstrap table + javascript template literal function): ... <th class ='publisher' data-field="book.publisher" data-formatter="renderPublisher">Publisher</th>... <script> var Publisher = "{{ Publisher }}"; var publisher = ''; function renderPublisher(value) { return `select style="width: 7em" name="" id=""> for (publisher in ${Publisher}) { <option value="eText" ${(value === 'eText') ? 'selected="selected"' : ""}> publisher</option>}</select>}` </script> But my for loop in javascript template literal function is not working, seems like I have some problem with the template literal usage in for loop. How to correct my function? -
How to get each order id contain multiple order products price calculate with quantity in django restframework?
def generate_order_id(): return uuid.uuid4().hex class Order(models.Model): STATUS = [ ('success', _('SUCCESS')), ('pending', _('PENDING')), ('failed', _('FAILED')), ] DELIVERY_STATUS = [ ('ordered', _('ORDERED')), ('pick_up', _('PICKED UP')), ('in_transit', _('IN TRANSIT')), ('out_for_delivery', _('OUT FOR DELIVERY')), ('delivered', _('DELIVERED')), ('returned', 'RETURNED') ] id = models.CharField(verbose_name='ORDER ID', max_length=64, default=generate_order_id, editable=False, primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='order_user', editable=False) product = models.ManyToManyField(Product, related_name='order_product') address = models.ForeignKey(DeliveryAddress, on_delete=models.CASCADE, related_name='order_address') amount = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(1000000)]) datetimestamp = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=STATUS) delivery_status = models.CharField(max_length=10) class OrderDetails(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_details') product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Meta: db_table = 'tbl_order_detail' class Product(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE) MRP = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(100000)]) price = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(100000)]) quantity = models.IntegerField() description = models.TextField() datetimestamp = models.DateTimeField(auto_now_add=True) class DeliveryStatus(models.Model): """ Delivery status of all orders """ user = models.ForeignKey(User, on_delete=models.CASCADE) order = models.OneToOneField(Order, on_delete=models.CASCADE) delivery_status = models.CharField(max_length=20, choices=DELIVERY_STATUS) timestamp = models.DateTimeField(auto_now_add=True, null=True, blank=True) class DeliveryCompletes(models.Model): """ here in this delivery completed only ordered product details and photo of product and price will automatically adding depend on delivery status order model and order details. """ PAYMENT = [ ('COD', 'CASH ON DELIVERY'), ('PREPAID', 'PREPAID'), ] STATUS = [ ('FULL', 'FULLY COMPLETED'), ('PARTIAL', 'PARTIAL COMPLETED') ] order = models.OneToOneField(DeliveryStatus, on_delete=models.CASCADE) payment_type … -
Django cannot find project app - cannot import x_app
I am working on moving a django project from a Windows environment to a Ubuntu environment. The project was stored in git and cloned into the Ubuntu environment. I am using virtualenv for a clean slate (same as on windows environment). Whether I run django-admin check or anything using python manage.py I get the below error: Traceback (most recent call last): File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/apps/config.py", line 244, in create app_module = import_module(app_name) File "/opt/bitnami/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'akita_app' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/bitnami/djangoenv/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/apps/config.py", line 246, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'akita_app'. Check that 'akitaapp.apps.AkitaAppConfig.name' is correct. The akita_app or akitaapp (same thing) that is missing is the the akitaapp folder. The project works perfectly in the Windows environment so I am guessing … -
Can I use ABC and Django Abstract classes together in Python?
I have a django abstract class: class AbstractModel(models.Model): date_added = models.DateField(auto_now_add=True) class Meta: abstract = True I want my concrete classes (Django Models) to subclass this abstract class, but I also want to make sure that all my concrete classes always implement very specific methods using abc. I tried doing this: class AbstractBaseClass(AbstractModel, metaclass=abc.ABCMeta): @abstractmethod def important_method(self): pass class MyDjangoModel(AbstractBaseClass): ... And I tried: class AbstractBaseClass(ABC): @abstractmethod def important_method(self): pass class MyDjangoModel(AbstractModel, AbstractBaseClass): Neither worked. They both say: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Is there a way to do this, or is this impossible? -
Django App Deploy on elastic beanstalk WSGI path issue
I am deploying the app then it gets severed health and 502 gateaway returns on browser. I checked out the logs lines I found these. Nov 9 01:15:38 web: ModuleNotFoundError: No module ImportError: Failed to find application, did you mean 'ecc/wsgi:application'? In .ebextensions folder django.config file look like below. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ecc/wsgi.py I also tried to give ecc/ecc/wsgi.py because of the folder structure --ecc |--accounts |--ecc --|__init__.py --|settings.py --|wsgi.py But it didn't worked either. What is the correct way to fix this issue. What I am missing here? -
Password Lock after Multiple Login Attempts for Django + simplejwt
I'm building Django app and implemented login function with django restframework simplejwt. Now trying to add function to lock out users after multiple wrong login attempts. Many people suggest django-axes package, but it only works with Django's default authentication backend, not with simplejwt's views. Any existing python packages help for this? Otherwise, how do you implement such a function with simplejwt? -
Django: No random letters in same name file uploaded
This is my code to let my user upload files, when more then one file is uploaded with the same condition by default random letters are added to the file name to avoid duplicate, is it possible to have the quantity number of file uploaded instead? so instead of having randomfilename randomfilename_jlCtWGb randomfilename_aOMtTeb have this randomfilename_1 randomfilename_2 randomfilename_3 Code: models.py def user_directory_path(instance, filename): filename = "word_file_%s.%s" % (instance.option, extension) return 'word_folder/{0}/{1}'.format(instance.option, filename) class Document(models.Model): option_choice = [ ('1', 'Option One'), ('2', 'Option Two') ] user = models.ForeignKey(UserInformation, on_delete=models.CASCADE) option = models.CharField(max_length=250, choices=option_choice, blank=True, null=True) original_filename = models.CharField(max_length=250, blank=True, null=True) docfile = models.FileField(upload_to=user_directory_path) def __str__(self): return word_db_' + self.option views.py @login_required def upload_file(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) uploaded_file= request.FILES if form.is_valid(): form.instance.user = request.user.userinformation form.instance.original_filename = uploaded_file['docfile'].name form.save() return redirect('upload_file') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() context = { 'form': form, 'message': message } return render(request, 'list.html', context) -
Encoding and decoding a base64 image in django
I have a django project in which I encode an image to Base64 via a serializer with the Base64ImageField field method There are no problems, but there is no way to get the image back:( In order not to get a 404 error in the serializer, I use SerializerMethodField and return STATIC_ROOT + obj.image.name . In this case, the code 200 is returned, but the picture is not displayed. I tried to decode through base64.b64decode(obj.image.encode('UTF-8')) and other methods of decoding and processing base64 drawings, but no one of them looks out the necessary code in the file. My decode serializer code to read: class DecodeSerializer(ModelSerializer): image = SerializerMethodField() class Meta: fields = "__all__" model = MyModel def get_image(self, obj): return STATIC_ROOT + obj.image.name My encode serializer: class EncodeSerializer(RecipesSerializer): image = Base64ImageField(max_length=None, use_url=True) class Meta: fields = "__all__" model = MyModel -
Allow user to access some part of a project depending on the role they have - Django
I just finished coding a django app that helps music producers coordinate projects and I am trying to solve a small problem I am facing. On a given project, users have specific roles (sound tech, drummer, production manager et cetera). Depending on their role, I want them to be able to see only some informations of the project. For example, the production manager should be able to see the project budget but the drummer no. How can I do it? I thought about using groups but I am not sure yet how. -
Field 'id' expected a number but got <SimpleLazyObject: <User: username>>
I have been stuck on this error for some time and I can't wrap my head around the problem or what it even means. I found some answers but none really solved my issue. Here is a brief desciption of what I do: In Javascript, I call this function with an int as a parameter such as: function follow (user_id) { // retrieves post for current selection fetch(`/follow/${user_id}`, { method: 'PUT', body: JSON.stringify({ follow: true }) }) } My url path, from url.py, is as follow: path('follow/<int:user_id>', views.follow, name="follow") finally, in views.py, this function is called: def follow(request, user_id): user = User.objects.get(id = user_id) if request.method == "PUT": data = json.loads(request.body) if data.get("follow") is not None: followed = Followed( user_id = user.id, followed_by_id = request.user, ) followed.save() return HttpResponseRedirect(reverse("index")) else: return HttpResponseRedirect(reverse("index")) I have tried a few different approaches such as removing the .value but I keep getting the following error: Field 'id' expected a number but got <SimpleLazyObject: <User: username>> I check along the way and the ID is an int all the way until it is passed to the model to be saved. I am using the abstractUser model. Let me know if more information is needed. Kind … -
Django views Passing a variable thru an object
i have the following situation: def detail(request, pk): """User can view an active survey""" try: survey = Survey.objects.prefetch_related("question_set__option_set").get( pk=pk, creator=request.user, is_active=True ) except Survey.DoesNotExist: raise Http404() questions = survey.question_set.all() for question in questions: if question.type != 'Text': option_pks = question.option_set.values_list("pk", flat=True) total_answers = Answer.objects.filter( option_id__in=option_pks).count() for option in question.option_set.all(): num_answers = Answer.objects.filter(option=option).count() option.pct = 100.0 * num_answers / total_answers if total_answers else 0 else: total_answers = Answer.objects.filter( question_id=question.pk).count() answers = Answer.objects.filter( question_id=question.pk).values_list("text", flat=True) for answer in question.answer_set.all(): num_answers = Answer.objects.filter( question_id=question.pk, text=answer.text).count() answer.pct = 100.0 * num_answers / total_answers if total_answers else 0 In the case of the question.type != 'Text', i can use the percentage in the template... but after the "else": , the percentage is not available for me on the templates... when im using the answer_set of the question instead of option_set does anyone know why?? HELP!! -
django pwa manifest error not reading service worker
I am creating a django pwa. In my local host, when I run my pwa, in my manifest report I get "No matching service worker detected. You man need to reload the page, or check that the scope of the service worker for the current page encloses the scope and the start URL from the manifest. " , but when I click on my service worker its there. serviceworker.js var staticCacheName = 'djangopwa-v'+ new Date().getTime(); self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '/', ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); manifest.json { "name": "Unlock Optimal Performance", "short_name" :"CMU", "description": "Fitness builder app", "theme_color" :"#639FCB", "background_color": "#fff", "display":"standalone", "start_url":"/", "icons":[ { "src": "/static/images/icons/icon-72x72.png", "sizes": "72x72", "type": "image/png", "purpose": "any" }, { "src": "/static/images/icons/icon-96x96.png", "sizes": "96x96", "type": "image/png", "purpose": "any" }, { "src": "/static/images/icons/icon-128x128.png", "sizes": "128x128", "type": "image/png", "purpose": "any" }, { "src": "/static/images/icons/icon-152x152.png", "sizes": "152x152", "type": "image/png", "purpose": "any" }, { "src": "/static/images/icons/icon-196x196.png", "sizes": "196x196", "type": "image/png", "purpose": "any" }, { "src": "/static/images/icons/icon-256x256.png", "sizes": "256x256", "type": "image/png", "purpose": "any" }, { … -
Filter queryset from beginning to a specific object
I know you can add [:n] on the end of a queryset to filter that queryset to be from the beginning to the nth object. E.g. qs = Item.objects.all() range = qs[:5] # Returns first five objects Is it possible to filter a queryset to be from the beginning to a specific object? e.g. qs = Item.objects.all() obj = Item.objects.get(pk="123") # How to return the qs from the beginning to obj? -
Delete all objects in Django except last N (N is big, about 1000)
What is fastest way to delete all objects except last 1000? I can do it slow way: last_events = Event.objects.filter(user=user).order_by('-created')[:1000].values_list('id', flat=True) Event.objects.filter(user=user).exclude(id__in=list(last_events)).delete() But I wouldn't like to load such long query to my DB. I thought I can't find ID of border element and delete all objects before that element: last_events = Event.objects.filter(user=user).order_by('-created')[:1000].last() But got: TypeError: Cannot reverse a query once a slice has been taken. I've also tried: last_events = Event.objects.filter(user=user).order_by('-created')[:1000][-1] But got: AssertionError: Negative indexing is not supported. -
Is there a way to upload images from ckeditor RichTextUploadingField to aws s3?
I am working on a personal portfolio website in Django and hosting it on heroku. I have been able to set up aws s3 for the static files and other images that will be uploaded to the website. The problem I am facing now is, images from the ckeditor are not being uploaded to aws s3. So the images vanish after a while. I read the ckeditor docs and it states to set 'AWS_QUERYSTRING_AUTH = False'. Doing this breaks my website's styling. Any ideas on how I could do this? It's been a while I worked with Django. Below is my settings.py. Thank you. import django_heroku import dj_database_url from pathlib import Path import os import environ # Initialise env variables env = environ.Env() environ.Env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # AWS S3 SETTINGS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_URL = '' AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_QUERYSTRING_AUTH = False # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on … -
Redirecting back to instance variable django
It seems like this should be a very common occurrence but I can't find anything about doing it on the internet. I have a page that renders once I input two bits of info: state and brand the views.py looks like this: def detail(request): try: if request.method == 'POST': state = request.POST['state'] brand = request.POST['brand'] territory_manager = TM.objects.filter(State__icontains=state).filter(Brand__icontains=brand), return render(request,'homepage/detail.html', {'state': state, 'territory_manager':territory_manager}) else: state = request.POST['state'] brand = request.POST['brand'] return render(request,'homepage/detail.html', f"No Results for {state} or {brand}") except TM.DoesNotExist: raise Http404("Info Does Not Exist") That page shows a filtered view of all the territory managers in my db that meet those two criteria. Once on that page I have an update button next to each territory manager that redirects to an update_territory_manager page where I can make updates to the territory manager. Once done updating I have a button that the user can click that is supposed to save the updated info to the db then redirect. I am trying to redirect back to the filtered view of all the territory managers that meet that criteria but the view function for the update page has no knowledge of that because that instance is in the previous views function (pictured … -
How to execute fetch paths without interfering with webpage pathname?
I am working on a Django project and got stuck on url patterns and routes. On index.html, the pathname is "" and the JS functions are working great. The fetch url tweets/${tweetid} is matching with Django API route url pattern tweets/<int:tweetid> and is working fine. However, on profile.html, the pathname is "profile/<int:userid>" and JS is not working here. The fetch url tweets/${tweetid} results the final path profile/tweets/<int:tweetid>. Since that is not in urls.py, I am getting an error. How can I execute my fetch and JS functions on any html page in this web application? -
ModuleNotFoundError: No module named 'django_celery_beat' in Django even if is installed and running
I want to see the Beat statistics in the admin panel so I want to have the beat in included in settings.py but even if it installed and works (async tasks not related to the web interface), I cannot add the django_celery_beat to the INSTALLED_APPS. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.app', 'apps.pps', 'apps.taskmgr', 'django_celery_beat', 'django_celery_results', ] import_module(entry) File "c:\users\paul\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_celery_beat' I use Python 3.8, celery 5.1.2, django-celery-beat 2.2.1, Django 3.26 and running on Windows 11. -
Django, python script run in page
I need run python script in backend i need to display it and catch user interact this on django page. Script is somthing like this: .... print("someting") if (input() == "y"): print("somethon") print("sas") data = input() It is possible to do something like this? I cant find solusions -
importing an exported list JSONField turns JSON to string if JSON list is empty
I am using this answer from a similar question. But I would like to treat any empty fields from the import-export file as an empty list instead of None. some_list_json= fields.Field(attribute='some_list_json', widget=JSONWidget(), column_name='some_list_json') When I try to export it, it doesn't show anything. And when I try to import and do some manipulation, it returns an exception. 'str' object has no attribute 'append' How do I get around this? -
Subdomain didn't send any data | ERR_EMPTY_RESPONSE | Heroku
I'm trying to connect my Heroku App via a custom GoDaddy subdomain. The subdomain is "subdomain" (for the sake of example). What I'm doing is, copying the DNS Target from Heroku and adding it in GoDaddy as a CNAME such that it is pointing to the DNS Target given by Heroku. Nonetheless, I'm getting the following error when going to www.subdomain.mysite.org I have previously created subdomains and connected them to GoDaddy with the DNS Target that Heroku provides. Don't know what I'm doing wrong. I tried to refresh the DNS but it's not working. -
Access Requests Method within Celery Task
Is it possible to access the requests.POST/GET methods within a celery task that's in a django project? I've read that it's not possible because celery can't serialized the requests JSON objects. Other than taking the data from the requests.POST['data'] object and passing them to the celery task, are there any other work arounds? def index(request): task = run_tasks.delay(request) # I would like to pass the request data to the task return render(request, 'example/index.html', {'task_id': task.task_id}) -
Do I need to do some registration of floatformat tag in django before using it?
I have the following piece of code <div>{{ context_findings["overdue_findings"] }} | {{ (context_findings["overdue_findings"] / context_findings["total_findings"] * 100)|floatformat }}%</div> but on executing it I get the error TemplateSyntaxError ("no filter named 'floatformat'",) I've tried doing something like <div class="pb-2">Overdue {{ 1.223|floatformat }}</div> to see if it works but I'm still getting the same error. Any ideas why this might happen? -
yaml: line 3: could not find expected ':' ERROR: failed to build: exit status 3
I get this error trying to deploy my django project on digital ocean. I really have no clue what to o from here. I don't know what code to post here as is required, but I need help. Trying to google elsewhere, I don't get the much needed help. yaml: line 3: could not find expected ':' ERROR: failed to build: exit status 3