Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set default value for a model field based on enum in Django?
I'm using Django 2.2.5 and have multiple choice fields based on enums in my models. For an unknown reason I now get a migration error when using an enum for choice field during migration: django.db.utils.OperationalError: (1067, "Invalid default value for 'protocol'") model.py from django.db import models # See class above from .utils import NetworkProtocolList class Networks(models.Model): ipv4 = models.GenericIPAddressField(blank=False, null=False) protocol = models.CharField(choices=NetworkProtocolList.choices(), max_length=20,default=NetworkProtocolList.ETH) class Meta: managed = True db_table = 'networks' utils.py from enum import Enum class NetworkProtocolList(Enum): ETH = 'Ethernet' MPLS = 'MPLS' @classmethod def choices(cls): return [(key.name, key.value) for key in cls] I issued manage.py makemigrations and subsequent manage.py migrate generated the following error: django.db.utils.OperationalError: (1067, "Invalid default value for 'protocol'") xxxx_auto_xxxxxxxx_xxxx.py # Auto generated migration file import my_.utils from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('my_app', 'yyyy_auto_yyyyyyyy_yyyy'), ] operations = [ migrations.AddField( model_name='networks', name='protocol', # Field definition here, pay attention to the default value field=models.CharField(choices=[('ETH', 'Ethernet'), ('MPLS', 'MPLS')], default=my_app.utils.NetworkProtocolList('Ethernet'), max_length=20), ), ] Than I edited migration file to manually set the default to a string instead of calling enum class: xxxx_auto_xxxxxxxx_xxxx.py # Edited migration file import my_.utils from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('my_app', 'yyyy_auto_yyyyyyyy_yyyy'), ] operations = [ … -
How to filter data dynamically by supply values from form using django
I want to filter Blog Post objects or records based on the Post Category and a User that uploaded the Post record, it gives me an error when I try to do filter, this is the error. ValueError at /dashboard/filter-post/ The QuerySet value for an exact lookup must be limited to one result using slicing. Here is my models.py class Category(models.Model): cat_name = models.CharField(max_length=100, verbose_name='Category Name') cat_desc = models.TextField(blank=True, null=True) def __str__(self): return self.cat_name class Meta(): verbose_name_plural='Category' class Post(models.Model): pst_title = models.CharField(max_length=150) pst_image = models.ImageField(blank=True, null=True, upload_to='uploads/') user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ManyToManyField(Category) content = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.pst_title @property def img_url(self): if self.pst_image: return self.pst_image.url on forms.py class FilterForm(forms.ModelForm): user = forms.ModelChoiceField( queryset=User.objects.all(), widget=forms.Select(attrs={'class': 'form-control'})) category = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), widget=forms.SelectMultiple(attrs={'class': 'form-control js-example-disabled-results'})) catch_bot = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)]) class Meta(): fields = ['user', 'category' ] model = Post on views.py def filter_post(request): post = FilterForm(request.GET) queryset = Post.objects.all() if post.is_valid(): user=post.cleaned_data.get('user') category=post.cleaned_data.get('category') if user and category: queryset = queryset.filter(user__username=user, category__cat_name=category) return render(request, 'backend/filter-post.html', {'query':queryset, 'post':post}) I am having challenges properly filtering this in my views any help? -
Image not uploading to aws s3 using django app
When a user registers on my website, a unique image is created internally(meaning, the user doesn't upload any image) and I want to upload that image to the s3 bucket in the name of the registered user. I have a single bucket in s3 that stores both static and media resources. The image that I create during the registration process is supposed to be uploaded to the media directory. views.py . . . img = qr.make_image() img.save('media/qrcodes/%s.png'%name) addnl.qr_gen = 'qrcodes/%s.png'%name # addnl is an instance of the form and qr_gen is a form field. addnl.save() ... models.py class UserModel(models.Model): ... qr_gen = models.ImageField(upload_to='qrcodes',default=None,null=True,blank=True) settings.py AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = config('AWS_S3_CUSTOM_DOMAIN') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = config('AWS_LOCATION') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) TEMP = os.path.join(BASE_DIR, 'temp') STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'project.storage_backend.MediaStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I've subclasses S3boto3Storage to store static and media files in separate directories and avoid overwriting. Hence, the DEFAULT_FILE_STORAGE = 'project.storage_backend.MediaStorage'. storage_backend.py from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False When a new user registers the account is created successfully, but the image … -
vuejs show real time log content on the page
Recently I get a requirement to show a log in frontend page via vuejs code. It's just to show a raw data of a log file. Now the file is served in Nginx and Django. And can be accessed via URL like http://myhost/media/file.log. But when I click the url in browser, the file is always downloaded instead of displayed in the page. Also the content is loaded all of the together. Can I implement the function just as bash command tail -f file.log in vuejs (Jenkins console has the same function)? It means display the file in the page with real time dynamic content. Many thanks. -
how does django cache queries indeed?
I like to know how django caching querySet work! for example how one can explain the following behaviour!? let say there is a model foo_model qs_1 = foo_model.objects.all() qs_2 = foo_model.objects.all() qs_x = foo_model.objects.filter(some_filed=some_value) when qs_1 is evaluated the qs_2 won't be evaluated, even though qs_1 is not qs_2 len(qs_1) len(qs_2 ) but qs_x will be evaluated! len(qs_x ) -
Django Celery scheduled task no output
I am working with Django and want a certain task to be runned twice a day (09:00 and 17:00). So I found Celery on the internet, and it looks good. I followed a few tutorials, and set it up. I've set a periodic task in the database, and it runs (for test) every minute. Or, it doesn't, it only says so: [2020-12-15 14:32:34,997: INFO/MainProcess] Scheduler: Sending due task ResumePentest (VulnManager.tasks.resumePentest) [2020-12-15 14:32:34,998: DEBUG/MainProcess] VulnManager.tasks.resumePentest sent. id->277c73a8-58bc-41ea-b2ba-4aa7af0c8b94 I don't think it actually runs, because I've tried some different "debugging" options: create file, print text, run my actual command. None of them seems to be working. My tasks.py file looks like this (for testing): from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def resumePentest(): f = open("/home/marvin/demofile2.txt", "a") f.write("Now the file has more content!") f.close() I run the celery worker with this command: celery -A VulnScanner beat -l DEBUG --scheduler django_celery_beat.schedulers:DatabaseScheduler Any hints? Not sure what I am doing wrong? If more info is needed, please let me know. Full output of celery worker: celery beat v5.0.4 (singularity) is starting. __ - ... __ - _ LocalTime -> 2020-12-15 14:44:26 Configuration -> . broker -> amqp://guest:**@localhost:5672// . loader -> celery.loaders.app.AppLoader … -
How to make my code insensitive to acronyms
I'm creating a website that shows available carparks in each college campus. How do I make the code insensitive to acronyms, e.g.g if the name of the campus is DCU Alpha? carparks.html <h2> {% if campus %} {{ campus }} {% else %} No such campus {% endif %} </h2> {% if campus %} {% if carparks %} <ul> {% for carpark in carparks %} <li>{{carpark.name}}: {{carpark.spaces}} spaces, {{carpark.disabled_spaces}} spaces for people with disabilities <br>Spaces available: {{ carpark.spaces_available }}<br><br> </li> {% endfor %} </ul> {% else %} <p>No carparks found</p> {% endif %} {% endif %} views.py def carparks(request): context = {} Base_URL = 'http://jfoster.pythonanywhere.com/carparks/' campus_name = request.GET['campus'] try: campus = Campus.objects.get(name__iexact=campus_name) except Campus.DoesNotExist: return render(request,"parkatdcu/carparks.html",context) carparks = Carpark.objects.filter(campus_id=campus) carpark_info = [] for carpark in carparks: URL = Base_URL + carpark.name r = requests.get(URL).json() if 'spaces_available' in r: spaces_available = r['spaces_available'] else: spaces_available = 'not available' carpark_info.append({ 'name': carpark.name, 'spaces': carpark.spaces, 'disabled_spaces': carpark.disabled_spaces, 'spaces_available': spaces_available } ) context['campus'] = campus_name.title() context['carparks'] = carpark_info return render(request,"parkatdcu/carparks.html",context) -
update the boolean field with hard condition - django rest framework
It's a little difficult. if some user like some post and then call the function allPost (in views.py) it should return is_liked=True in serializer.data. like this: { "id": 48, "body": "like me", "date": "2020-12-15T11:39:58.233912+06:00", "user": {}//objects "total_likes": 4, "liked_by": {}//object "total_comments": 0, "is_liked":true }, { "id": 47, "body": "hello", "date": "2020-12-15T10:53:56.047665+06:00", "user": {},//object "total_likes": 2, "liked_by": [ { "first_name": "", "last_name": "" }, { "first_name": "test3", "last_name": "three" } ], "total_comments": 0, "is_liked": false }, models.py: class Post(models.Model): id = models.AutoField(primary_key=True) body = models.TextField(max_length=10000) date = models.DateTimeField(auto_now_add=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) liked_by = models.ManyToManyField(User, blank=True, related_name='liked_by') is_liked = models.BooleanField(default=False) class Meta: ordering = ['-date'] serializers.py: class PostSerializer(serializers.ModelSerializer): user = UserSerializers() total_likes = serializers.SerializerMethodField() liked_by = SimpleUserSerializer(many=True, read_only=True) total_comments = serializers.SerializerMethodField() class Meta: model = Post fields = ('id','body','date','user','total_likes','liked_by','total_comments','is_liked') def get_total_likes(self, instance): return instance.liked_by.count() def get_total_comments(self, instance): return instance.comment_set.count() urls.py: path('myapi/likepost/<str:pk>/', views.likePost, name='likePost'), views.py: @api_view(['GET']) @permission_classes((IsAuthenticated,)) def allPost(request): user = request.user.id allpost = Post.objects.all() serializer = PostSerializer(allpost, many=True) liked = Post.objects.filter(liked_by__id=user).values_list('id', flat=True) #--> i think, code should be written here return Response(serializer.data) @api_view(['POST']) @permission_classes((IsAuthenticated,)) def likePost(request, pk): user = request.user.id post = Post.objects.get(id=pk) previous_user = post.liked_by.all().values_list('id', flat=True) liked_by = [user] for i in previous_user: liked_by.append(i) data = {'liked_by':liked_by} serializer = … -
AttributeError: 'ShiftChangeFilter' object has no attribute 'values_list'
Hello Everyone I am getting Attribute Error. I have one Django based webpage where I am using Django filter to search user result and trying to implement functionality for download filtered result only in order to achieve this I am trying to pass Filter class, in my existing download views. (Earlier my download view is responsible to download all model-based data). My code is from .models import * import django_filters class ShiftChangeFilter(django_filters.FilterSet): id = django_filters.NumberFilter(label="DSID") class Meta: model = ShiftChange fields = ['ConnectID', 'EmailID','id','SerialNumber','Project_name',''] My view responsible to download xls file: from django.utils import timezone now_aware = timezone.now() import xlwt,openpyxl def exportgenesys_data(request): allgenesys = ShiftChange.objects.all() genesys_filter = ShiftChangeFilter(request.GET,queryset=allgenesys ) print('download:',genesys_filter.qs) response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="Genesys_ShiftTiming.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('GenesysShiftChange Data') # this will make a sheet named Users Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['id', 'ConnectID', 'Shift_timing', 'EmailID', 'Vendor_Company', 'Project_name', 'SerialNumber', 'Reason', 'last_updated_time'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = genesys_filter.values_list('id', 'ConnectID', 'Shift_timing', 'EmailID', 'Vendor_Company', 'Project_name', 'SerialNumber', 'Reason', 'last_updated_time') for row in rows: row_num += 1 for col_num … -
Field 'id' expected a number but got a dict
I'm getting a error when run seed_responses command. Complete error std error: $ ./manage.py seed_responses --number 15 Traceback (most recent call last): File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/src/secret/api/core/management/commands/seed_responses.py", line 36, in handle seeder.execute() File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django_seed/seeder.py", line 157, in execute entity = self.entities[klass].execute(using, inserted_entities) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django_seed/seeder.py", line 101, in execute obj = manager.create(**faker_data) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 447, in create obj.save(force_insert=True, using=self.db) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base updated = self._save_table( File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/base.py", line 933, in _do_insert return manager._insert( File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File … -
Django downloading image using ImageField
I am trying to create a Django app that allows user to upload and download images from /images/ folder (similar to a static folder in my app). My upload part of the app uses ImageField to store the image filepath into MySQL database: models.py class ImagefieldModel(models.Model): title = models.CharField(max_length = 200) img = models.ImageField(upload_to = "images/") class Meta: db_table = "imageupload" forms.py class ImagefieldForm(forms.Form): name = forms.CharField() image_field = forms.ImageField() fileupload.html {% extends "main/header.html" %} {% block content %} <head> <title>Django File Upload</title> </head> <body> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> </body> {% endblock %} views.py def imgupload(request): context = {} if request.method == "POST": form = ImagefieldForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data.get("name") img = form.cleaned_data.get("image_field") obj = ImagefieldModel.objects.create( title = name, img = img ) obj.save() print(obj) messages.info(request, f"image uploaded successfully!") return redirect("main:basehome") else: form = ImagefieldForm() context['form'] = form return render( request, "main/fileupload.html", context) For the download part of my app, I want the app to list down all images from the /image/ folder and users can choose an image to download into their download folder. How do I do that in Django while using ImageField? -
Files uploaded through a "multipart/form-data" form aren't stored anywhere
I've been struggling with this for some time and it makes me think that what I want to achieve is done differently in Django. I have a model (Album) with the following definition: class Album(models.Model): building_id = models.ForeignKey(Building, on_delete=models.CASCADE) name = models.TextField() I have another model (Photo): class Photo(models.Model): album_id = models.ForeignKey(Album, on_delete=models.CASCADE, related_name="photos") path = models.ImageField(upload_to="photos") You can probably see where this is going: I want to be able to upload many photos at once when creating a photo album. To access my Album data through Django admin, I register it: @admin.register(models.Album) class AlbumAdmin(admin.ModelAdmin): form = forms.AlbumForm And the associated form, which apparently must inherit from ModelForm: class AlbumForm(forms.ModelForm): class Meta: model = Album fields = ["building_id", "name", "photos"] building_id = forms.ModelChoiceField(queryset=Building.objects.all()) name = forms.CharField() photos = forms.FileField(widget=forms.ClearableFileInput(attrs={"multiple": True})) After this setup, going to http://localhost:8000/admin/api/album/add offers me a form (with enctype="multipart/form-data") where I can upload my files. Pressing the submit button succesfully create the new album, but the uploaded photos are nowhere to be found (my ${MEDIA_ROOT}/photos is still empty), and obviously no Photo model is created. What would be the best "Django way" of doing it, and how could I achieve any of the following: Whenever a new … -
Django queryset count by attribute
Is there a simple, or built-in mechanism in Django to perform a queryset where from the queryset output I will be able to do some statistics based on an specific attribute ? Here is my example: models.py class Transaction(models.Model): transactionType = models.CharField(max_length=2) value = models.DecimalField(max_digits=7, decimal_places=2) transactionDate = models.DateField() owner = models.ForeignKey(User, related_name="transactions", on_delete=models.CASCADE) def __str__(self): return self.transactionDate serializers.py class TransactionSerializer(serializers.ModelSerializer): owner = UserFilteredSerializer(many=False) class Meta(): model = Transaction fields = ( 'pk', 'transactionType', 'value', 'transactionDate', 'owner' ) views.py class TransactionList(generics.ListCreateAPIView): parser_classes = (MultiPartParser, FormParser) serializer_class = TransactionSerializer name = 'transaction-list' def get_queryset(self): queryset = Transaction.objects.all() transactionType = self.request.query_params.get('transactionType', '') return queryset.filter(transactionStatus=transactionStatus).order_by('-transactionDate') My View returns output as below: [ { "pk": 261, "transactionType": "ch", "transactionDate": "2020-11-01" "value": "30.00", "owner": { "username": "john", "first_name": "John", "last_name": "Smith", } }, { "pk": 262, "transactionType": "ch", "transactionDate": "2020-11-01" "value": "40.00", "owner": { "username": "andrew", "first_name": "Andrew", "last_name": "Kowalsky", } }, { "pk": 263, "transactionType": "ch", "transactionDate": "2020-11-01" "value": "50.00", "owner": { "username": "john", "first_name": "John", "last_name": "Smith", } }, ] But I would like to get number of transactions for each individual user. Is it a simple way to get this in django like this ? return queryset.filter(transactionStatus=transactionStatus).count(by username) -
Optimising infrastructure for Django application that utilizes Pandas
My company has built a backend Django application that utilizes pandas data frames. Before I jump in as a DevOps Engineer, the application was hosted on Digital Ocean on a machine with 8GB of RAM and 4vCPUs. According to some metrics, the application is utilizing less than 10% CPU and around 37% of RAM I was tasked with migrating the application to GKE, which I am currently monitoring how it is doing. I am using the normal E2 VMs as nodes and I have allocated the container 1GB of RAM and I have left the CPU to be of the default value. According to the metrics, CPU usage is really low and the RAM usage is high but it never drops even when there are no requests to the application, A developer also complained that the application hosted on GKE is quite slow compared to the application hosted on Digital Ocean. My question is; how can I better engineer the infrastructure while keeping costs in mind? Should I add more CPUs and RAM? Should I use other VM types for Nodes? Any tips or suggestions are highly welcomed! Thank you. -
Custom Queryset constructor loses value of argument
Django. I want to prevent my future self from overwriting a certain property of the Cable class in the database. I wrote a custom Django QuerySet that accepts a field name in the constructor and which will prevent updates on that field. However, in the constructor, the argument field_name is well received (as evidenced by the correct output from print), but then the Exception is also raised, meaning that the variable was instantly changed to None. What devilry? Note I also tried putting *args in the constructor signature. class PreventChangeQuerySet(models.QuerySet): def __init__(self, field_name, **kwargs): self._field_name = field_name print(f"Field name: {self._field_name}") if self._field_name is None: print(self._field_name) raise Exception("A field name must be set") self._field_name = field_name super().__init__(**kwargs) def update(self, *args, **kwargs): if kwargs.get(self._field_name): raise Exception("This field may not be updated") super().update(*args, **kwargs) class Cable(models.Model): __original_short_name = None # For keeping track of changes objects = PreventChangeQuerySet(field_name="short_name").as_manager() output: ./manage.py shell_plus Field name: short_name Traceback ... TypeError: __init__() missing 1 required positional argument: 'field_name' -
Django stripe.error: Invalid card object: must be a dictionary or a non-empty string
I am trying to take a Stripe payment but I get an InvalidRequestError everytime I try to make a payment. The payment is for a set amount of 5 Euros. I am using the credit card number 4242 4242 4242 4242 to test the payment. My form is valid, but when it sends the payment request to Stripe I get the errors and it looks like stripe_id is blank. Any ideas? checkout.html: {% extends "base.html" %} {% load static from staticfiles %} {% load bootstrap_tags %} {% block head_js %} <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script type="text/javascript" src=""> //<![CDATA[ Stripe.publishableKey = '{{ publishable }}'; // ]]> </script> <script type="text/javascript" src="{% static 'js/stripe.js' %}"></script> {% endblock %} {% block content %} <form action="{% url 'checkout' %}" method="post" id="payment-form" class="col-md-6 col-md-offset-3"> <legend>Payment Details</legend> <div id="credit-card-errors" style="display: none;"> <div class="alert-message block-message error" id="stripe-error-message"></div> </div> <div class="form-group col-md-6"> {{ payment_form|as_bootstrap }} </div> {% csrf_token %} <div class="form-group col-md-12"> <input class=" btn btn-primary" id="submit_payment_btn" name="commit" type="submit" value="Submit Payment of 5 Euros"> </div> </form> {% endblock %} forms.py: from django import forms class MakePaymentForm(forms.Form): print("MakePaymentForm...") MONTH_CHOICES = [(i, i) for i in range(1, 12)] YEAR_CHOICES = [(i, i) for i in range(2019, 2040)] credit_card_number = forms.CharField(label='Credit Card Number', … -
Is there any option to filter data by model's filed in django python?
I am new to Django, Is there any option to display data by choice? I am able to filter by category but I have to filter by choices or model's field. Or is there any option to multiple filters in one template? Or can we filter by using two foreign keys in one model? Here is my Product model where I have used filed (member) for the filter but I could not do that then I have used another model for the filter. class Product(models.Model): MEMBER = ( ('For Kids', 'For Kids'), ('For Lover', 'For Lover',), ('For Teacher', 'For Teacher'), ('For Boss', 'For Boss'), ) category = models.ForeignKey(Category, related_name='products', on_delete=models.PROTECT) member = models.CharField(max_length=200,choices = MEMBER) title = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%d/%m/%Y', blank =True) description = models.TextField(blank=True) price = models.IntegerField(default=0) stock = models.PositiveIntegerField() available = models.BooleanField(True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-title',) index_together = (('id','slug'),) def __str__(self): return self.title and my category model : class Category(models.Model): title = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) image = models.ImageField(upload_to='products/%d/%m/%Y', blank =True) parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.PROTECT) class Meta: unique_together = ('slug', 'parent',) ordering = ('title',) verbose_name = 'category' verbose_name_plural = 'categories' … -
ajax call returns 'undefined' during first call only
i am trying to make a desktop like text input help using datatable.in table with keyboard navigation. For that i am dynamically changing the source and also change the header column. So far i have succeeded in that except getting dynamic column header. For getting the column header based on the text input header, i am making an ajax call and getting the list of column header. the issue is during first call ajax returns 'undefined' but in the second call it shows the value. i understand this is pertaining to the asynchronous call but not sure how to handle this. Below is my code snips. AJAX call in external .js **function ajaxCall(ipUrl, callType = "POST", dataIn) { return $.ajax({ url: ipUrl, type: callType, data: dataIn, dataType: "json", success: function (response) { retData = response.data; alert('success'+ retData); return retData; }, error: function (err) { alert("fail" + JSON.stringify(err)); }, //error }); //alert('in js'+ retData); //return retData; }** HTML Script tag **$("#btn").click( function (e) { var tData = { action: 'getHeader', csrfmiddlewaretoken: 'Gys4TSx3ODJLcMDuXlSvS7DopVZr1HWEDLg9AlJsARXp7wmUGAxxKwo6uLVXIrf2', } tmp = ajaxCall('dyncolheader','GET',tData) ; if (tmp == undefined) { alert('second call'); tmp = ajaxCall('dyncolheader','GET',tData) ; alert('tmp' + tmp); } else { alert('else' + tmp); } });** Django View … -
How to ignore a postgresql generated field in Django Admin update queries
I have this model in Django: class Job(models.Model): id = models.BigAutoField(primary_key=True) start_time = models.DateTimeField(blank=True, null=True) end_time = models.DateTimeField(blank=True, null=True) run_time = models.IntegerField(editable=False, blank=True) The run_time field is a generated field in Postgresql and calculates the difference between end_time and start_time. I set it up here as editable=False. If create an Admin page for this, whenever i want to create or change a "job" i get this error ProgrammingError at /admin/model/job/1/change/ column "run_time" can only be updated to DEFAULT DETAIL: Column "run_time" is a generated column. Please note the field has editable=False I have tried many options: class JobAdmin(admin.ModelAdmin): fields = [ 'start_time','end_time'] exclude = ('run_time',) readonly_fields = ('run_time',) use_on_insert = [ 'submit_time', 'start_time'] use_on_update = [ 'submit_time', 'start_time'] I am still getting the error. How can I ignore the run_time field from the update and insert queries? -
Check if value of selected option is valid
I am very much a beginner at testing and defensive design so apologies in advance if my attempt seems naive. One of the fields in my form is a ModelChoiceField and renders a select widget with options based on the objects in the queryset. In dev tools a user could change the value of the selected option and click submit. Is there a way to protect from this and send an error in the template, the same way an emailchoicefield would flag a valid email format in an EmailInput? So far I have this in my form class (form.py ) but it doesnt work: def clean_destination(self): """ Validation to see that inputted date is from the queryset """ destination = self.cleaned_data.get('destination') if not Destination.objects.get(pk=destination) raise forms.ValidationError("This is not a valid option") return destination -
Django_Tables2 Accessor / Related Fields
I have the following constellation of Tables, which are linked via FK's: (omitted a few fields for better readability) class ProductDetail(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) product_detail = models.CharField(max_length=100, primary_key=True, verbose_name='Product Detail Name') materialcode = models.CharField(max_length=20, blank=False, null=False, verbose_name='Material-Code') billing_model = models.ForeignKey(BillingModel, on_delete=models.CASCADE) .... -------------- class MinimumRevenue(models.Model): operator = models.ForeignKey(Operator, on_delete=models.CASCADE) billing_model = models.ForeignKey(BillingModel, on_delete=models.CASCADE) minimum_revenue = models.DecimalField(decimal_places=2, max_digits=20, verbose_name='Minimum Revenue') currency = models.ForeignKey(Currency, on_delete=models.CASCADE) product_detail = models.ForeignKey(ProductDetail, on_delete=models.CASCADE, verbose_name='Product Detail') event_type_assignment = models.CharField(max_length=100, verbose_name='Event Type Assignment') start_date = models.DateField(blank=False, null=False, verbose_name='Start Date', default=get_first_of_month) end_date = models.DateField(blank=False, null=False, verbose_name='End Date') .... And a Table (Django_Tables2) which points to the MinimumRevenue Model (which works as designed), now I would like to also show some more related fields in my Table: class MinimumRevenueTable(tables.Table): edit = tables.LinkColumn('non_voice:minimum_revenue_update', orderable=False, text='Edit', args=[A('pk')]) invoice_text = tables.TemplateColumn( '<data-toggle="tooltip" title="{{record.context}}">{{record.invoice_text|truncatewords:2}}') start_date = tables.DateColumn(format='Y-m-d') end_date = tables.DateColumn(format='Y-m-d') foreigncolumn = tables.Column(accessor='productdetail.materialcode') class Meta: model = MinimumRevenue template_name = "django_tables2/bootstrap4.html" fields = ('operator', 'billing_model', 'minimum_revenue', 'product', 'product_detail', 'event_type_assignment', 'start_date', 'end_date', 'invoice_text', 'currency', 'foreigncolumn') attrs = {'class': 'table table-hover', } The foreigncolumn column is never filled, just showing '-', I also tried it with other columns of ProductDetail, but never get any result, would really appreciate any solutions! -
Printing an ERD for an specific Django app
I've had good results using the django-extensions package, more specificaly, the graphviz module. It allows to print the full cover of entities. What I couldn't do yet, is to print only some specific apps or the related entities with only one model. Already tried the documentation instruction: $ python manage.py graph_models foo bar -o specific_app_erd.png But without the expected result, only mapping the complete structure of entities, not the isolated ones. I've already tried different inputs for the app_name_arg: the name from installed_apps, the relative.path.from.base_dir, but couldn't get the selected one yet. -
Django - dynamic model for TemplateView class-based
I want to switch between two models depending on which route I am in. I am overwriting get_queryset() function to return the correct model: class DynamicModelView(TemplateView, PageDescriptionListingMixin): model = None template_name = 'dynamic_model.html' context_object_name = "accounts" def get_context_data(self, **kwargs): context = super(DynamicModelView, self).get_context_data(**kwargs) self.add_page_text_to_context(context) return context def get_queryset(self): if '/dynamic_user/' in self.request.path: model = UserAccount else: model = AdminAccount return model.objects.first() As you can see in get_context_data I am injecting an object in context for AdminAccount but inside template I can't see it! in fact if I changed model from None to AdminAccount then it appears which I want that to happen dynamically. -
Integrate Intro.js with Django
I use Intro.js in a Django website. The Intro.js is used on the navigation bar which appears and stuck on every page. <html> <script type="text/javascript"> $("#description").click(function (e) { e.preventDefault(); introJs().start(); }); </script> <style> #navigation-bar { /* position: -webkit-sticky; */ position: sticky ; width: 100%; top: 0px; background-color: #93C1DB; z-index: 9999; } </style> <div id="navigation-bar"> <a href="{% url 'AAA_page' %}" data-intro="This is AAA" data-step="1">AAA</a> <a href="{% url 'BBB_page' %}" data-intro="This is BBB" data-step="2">BBB</a> <a href="{% url 'CCC_page' %}" data-intro="This is CCC" data-step="3">CCC</a> </div> {% block content %}{% endblock %} </html> If the attribute for the position is "-webkit-sticky", then words can be displayed, but the navigation bar will not fix at the top, it will move up to exit the page while scrolling down the page: If the attribute for the position is "sticky", then the navigation will fix at the top while scrolling down the page, but the text will be covered: My objective is to make the text can be displayed and the navigation is fixed on the top when scrolling down the page. Could you give me any suggestion, thank you! -
django react authentication token
I am building a react-native app with Django backend, could someone suggest a Django authentication token tutorial for sign in and signup, since I am new to Django and I got confused among all the youtube tutorials!