Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get composite of two tables in Django Queryset?
Is there a way to do the equivalent of a full outer join in Django (I think I've read that full outer joins are not supported). My scenario is that I have three tables: Staff / WeekList / WeeksCompleted The relevant fields I'm trying to work with are: Staff table - Staff Number. WeekList table - Week Start date. WeeksCompleted table - Week Start date and Staff Number. Basically, everyone should have an entry in the WeeksCompleted table (if they're still active, that is, but that's not pertinent for this question). The queryset I would like to produce is a list of Staff who have missing weeks in the WeeksCompleted table. I can get the result I want using SQL queries but it involves a full outer join on the Staff and WeekList tables. I was wondering if anyone knows of a way to do this using the queryset functions? -
Django, Ajax and JS . How to prevent page reloads and jump ups to the top of the page when i submit a comment
I followed a solution on how to get Django comment form to submit without page reloading and jumping to the top of the page. I tried many solutions online and offline but still no solution. I am new to Django Backend and Ajax, I will be happy if someone can help on how to deal with this. Thanks in Advance. JS AJAX $( document ).ready(function() { $(`.comment-form${post_id}`).submit(function() { $.ajax({ data: $(this).serialize(), type: $(this).attr('method'), url: $(this).attr('action'), success: function(response) { $(); }, error: function(response) { console.log('error', response) } }); return false; }); }); VIEWS from django.shortcuts import render, redirect from .models import Post, Like from django.contrib.auth.models import User from .forms import CommentModelForm from django.http import JsonResponse # Create your views here. def post_comment_create_and_list_view(request): qs = Post.objects.all() user = User.objects.get(pk=request.user.pk) #Comment form c_form = CommentModelForm() if 'submit_c_form' in request.POST: c_form = CommentModelForm(request.POST) if c_form.is_valid(): instance = c_form.save(commit=False) instance.user = user instance.post = Post.objects.get(id=request.POST.get('post_id')) instance.save() c_form = CommentModelForm() context = { 'qs': qs, 'user':user, 'c_form':c_form, } return render(request, 'posts/main.html', context) HTML <form action="" method="POST" class="comment-form" id='{{obj.id}}'> {% csrf_token %} <div class="input-group"> <input type="hidden" name="post_id" value={{obj.id}}> {{ c_form }} <div class="input-group-append"> <button type="submit" name="submit_c_form" class="btn btn-md u-btn-white g-color-red g-text-underline-hover g-brd-gray-light-v3 g-brd-none g-brd-top">Post</button> </div> </div> </form> -
Django multiple AJAX queries for images
I made a button the user can click and it makes a AJAX GET request to the backend class Image. The response is the image url. I paste the url into a image tag and display it on the template models.py class Image(models.Model): img = models.ImageField() views.py def ajax(request): from django.http import JsonResponse if request.is_ajax(): image = request.FILES.get('data') aaa = Image.objects.get(id=1) aaa = str(aaa.img.url) return JsonResponse({'image_query': aaa}, status=200) return render(request, 'components/ajax.html') AJAX (template) <button id="getData" class="btn btn-success">Get</button> <div id="seconds"></div> ... <script> $(document).ready(function () { $('#getData').click(function () { $.ajax({ url: 'ajax', type: 'get', data: { data: $(this).text() }, success: function (response) { $('#seconds').append('<img src="' + response.image_query + '" width="300">') } }) }) }) </script> Everything works fine and the image is rendered to the template! Now I dont want to query the image with ID=1, I want all images to be fetched to the template. I tried to do by adding a for loop into the views.py but it only returns the first element. if request.is_ajax(): image = request.FILES.get('data') for i in range(1, 5): aaa = Image.objects.get(id=i) aaa = str(aaa.img.url) return JsonResponse({'image_query': aaa}, status=200) I don't know what to modify that it will query every image in the DB. Does someone … -
Callback function of django leflet in forms
I am using django with django-leaflet. Normaly i can use the map.init callback function to add json layers. But when i am creating a form with a map in it django-leflet is using the callback function for the leaflet-draw. Anybody know how i can add functions for a json layer in the created callback function? <script> var geodjango_id_geom = {}; geodjango_id_geom.fieldid = 'id_geom'; geodjango_id_geom.modifiable = true; geodjango_id_geom.geom_type = 'LineString'; geodjango_id_geom.srid = 4326; function id_geom_map_callback(map, options) { geodjango_id_geom.store_class = L.FieldStore; geodjango_id_geom.precision = options.djoptions.precision; (new L.GeometryField(geodjango_id_geom)).addTo(map); }; -
django-rest-auth: LOGOUT_ON_PASSWORD_CHANGE: Is this session based or token based
I am using django-rest-auth I am implementing password change. I found this option: at https://django-rest-auth.readthedocs.io/en/latest/api_endpoints.html LOGOUT_ON_PASSWORD_CHANGE = False to keep the user logged in after password change I wanted to understand the flow. I sent my password details old_password new_password1 new_password2 to the endpoint /rest-auth/password/change/ (POST) curl --location --request POST "http://127.0.0.1:8000/rest-auth/password/change/" \ --header "Authorization:Token a42fdd3938ad24d8abd064d3fedhsh599115e38b6a" \ --header 'Content-Type: application/json' \ --data-raw '{ "old_password": "oldP" "new_password1": "newP" "new_password2": "newP" }' Now what happens to my token on LOGOUT_ON_PASSWORD_CHANGE = True -
how to handle failed recurring payments in razorpay?
I was trying to use the recurring module of Razorpay on the Django website. Although I successfully integrate Razorpay, I have no idea about how to handle the failure of recurring payments. Does anyone know how to deal with it? I mean how can I get a response that payment is failed for a particular user -
Is it possible to print superscript and subscript in the same characterspace in python for use in a Django template?
I'd like to print element symbols, with the mass number represented in superscript and the atomic number as a subscript, in the single character space directly preceding the element's letter. I'm currently using: SUP = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹") atom = f"{1}{H}{1}".translate(SUP) print(atom) This is better than nothing, but I'd like both numbers to be in line, as they would usually be. I know that unicode wizardry exists to create fractions. Is there either a python library, or a special unicode character which can do this for me? Unicode is ideal, because I can rely on it working in my Django templates. Search terms such as 'composite superscript and subscript unicode' and similar have so far yielded nothing. -
AttributeError: module 'tokenize' has no attribute 'open'
File "C:\Users\sidiy\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 193, in _run_module_as_main return run_code(code, main_globals, None, File "C:\Users\sidiy\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 86, in run_code exec(code, run_globals) File "C:\Users\sidiy\Documents\django_app\obj\Scripts\pip.exe_main.py", line 5, in File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_internal_init.py", line 40, in from pip._internal.cli.autocompletion import autocomplete File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_internal\cli\autocompletion.py", line 8, in from pip._internal.cli.main_parser import create_main_parser File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_internal\cli\main_parser.py", line 7, in from pip._internal.cli import cmdoptions File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_internal\cli\cmdoptions.py", line 24, in from pip._internal.models.search_scope import SearchScope File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_internal\models\search_scope.py", line 11, in from pip._internal.utils.misc import normalize_path, redact_password_from_url File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_internal\utils\misc.py", line 21, in from pip.vendor import pkg_resources File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_vendor\pkg_resources_init.py", line 84, in import('pip._vendor.packaging.requirements') File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_vendor\packaging\requirements.py", line 9, in from pip._vendor.pyparsing import stringStart, stringEnd, originalTextFor, ParseException File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_vendor\pyparsing.py", line 5257, in _escapedPunc = Word( _bslash, r"[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1]) File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_vendor\pyparsing.py", line 1442, in setParseAction self.parseAction = list(map(_trim_arity, list(fns))) File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_vendor\pyparsing.py", line 1211, in _trim_arity this_line = extract_stack(limit=2)[-1] File "c:\users\sidiy\documents\django_app\obj\lib\site-packages\pip_vendor\pyparsing.py", line 1195, in extract_stack frame_summary = traceback.extract_stack(limit=-offset+limit-1)[offset] File "C:\Users\sidiy\AppData\Local\Programs\Python\Python38-32\lib\traceback.py", line 211, in extract_stack stack = StackSummary.extract(walk_stack(f), limit=limit) File "C:\Users\sidiy\AppData\Local\Programs\Python\Python38-32\lib\traceback.py", line 366, in extract f.line File "C:\Users\sidiy\AppData\Local\Programs\Python\Python38-32\lib\traceback.py", line 288, in line self._line = linecache.getline(self.filename, self.lineno).strip() File "C:\Users\sidiy\AppData\Local\Programs\Python\Python38-32\lib\linecache.py", line 16, in getline lines = getlines(filename, module_globals) File "C:\Users\sidiy\AppData\Local\Programs\Python\Python38-32\lib\linecache.py", line 47, in getlines return updatecache(filename, module_globals) File "C:\Users\sidiy\AppData\Local\Programs\Python\Python38-32\lib\linecache.py", line 136, in updatecache with tokenize.open(fullname) as fp: AttributeError: module 'tokenize' has no attribute … -
Django - Filtering by generic foreign key's attribute
I have a model structure (truncated models to simplify): class Product(models.Model): style_id = models.CharField(max_length=20, unique=True, primary_key=True) class ShoeProduct(models.Model): Product = models.ForeignKey(Product, default=1, on_delete=models.CASCADE, verbose_name="Product", related_name="shoe_product") colorway = models.CharField(max_length=30, verbose_name="Colorway", blank=True, null=True) class InventoryItem(models.Model): unique_sku = models.SlugField(blank=True, verbose_name="Inventory System SKU") location = models.CharField(max_length=10, blank=True, null=True, verbose_name="Warehouse Location") # GenericForeignKey fields for SKU models content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) object_id = models.CharField(max_length=50) content_object = GenericForeignKey('content_type', 'object_id') class ShoeSKU(models.Model): ShoeProduct = models.ForeignKey(ShoeProduct, verbose_name="Style Number", on_delete=models.CASCADE) sku = models.CharField(max_length=50, verbose_name="SKU") condition = models.CharField(max_length=25, choices=condition_choices) inventory_items = GenericRelation(InventoryItem) I would like to filter InventoryItem for objects that have a ShoeSKU.condition of 'NWB'. InventoryItem's can also be related to ClothingSKU (not shown above, which also have a condition attribute.) I've tried: filtered = InventoryItem.objects.filter( content_type=ContentType.objects.get_for_model(ShoeSKU).id, content_object__condition='NWB') but this returns error: django.core.exceptions.FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. I also would like to do something like to add an argument to include Product.style_id in the filtered queryset -
Can django widget_tweaks render out input as textarea box?
I want to render out an input box as textarea with widget_tweaks in Django. This is my code: <div class="form-row"> <div class="form-group col-md-6"> <label>More information *</label> {% render_field form.info class="form-control" %} </div> </div> Everything is working fine, but it renders out as <input> tag. Is there any way to render it out as <textarea> without changing the models from CharField to TextField? I want to have a bigger box so there is more space to write the text. I know I can add a class that could change the size of the input box, but the textarea tag would be easier. -
Adding Google Sign-In To Web App & Retrieve Group Membership From GSuite?
For an internal web app I'm developing in Python/Django I need to retrieve the user's group membership from GSuite and grant/deny the user access to specific webpages depending on what group they have access to. I've read about how to add a Google Sign-in button, which works as expected: https://developers.google.com/identity/sign-in/web/sign-in However, the user's basic profile doesn't give me the group memberships. I've checked this documentation page (https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile) but can't see any reference to group memberships. Does that therefore mean I need to connect to the GSuite Admin SDK? If so, can I grant a service account read-only permission to retrieve the group memberships? Reading this (https://developers.google.com/admin-sdk/directory/v1/guides/delegation) and the 0Auth 2.0 authorisation scopes (https://developers.google.com/identity/protocols/oauth2/scopes#admin-directory) seems to suggest I can only grant the service account domain-wide access to administer GSuite Users, which would be a security concern. -
Django rest framework IntegrityError(1048, "Column 'Board_id' cannot be null")
The error below occurs when attempting to create a comment. enter image description here And my code is as follows. I want to know the solution. Help me. I'm such a beginner. models.py class Board(models.Model): b_no = models.AutoField(primary_key=True) b_title = models.CharField(max_length=255) b_note = models.TextField(null=True, help_text="") b_writer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) parent_no = models.IntegerField(default=0, null=True) b_date = models.DateTimeField(auto_now_add = True, blank=True, null=True) b_count = models.PositiveIntegerField(default=0) usage_flag = models.CharField(null=True, max_length=10, default='1') class Comment(models.Model): Board = models.ForeignKey(Board, on_delete=models.CASCADE) c_writer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) c_note = models.TextField(null=True, help_text="") c_date = models.DateTimeField(auto_now_add = True, blank=True, null=True) serializers.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['c_writer', 'c_note', 'c_date'] class CommentCreateSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['c_writer', 'c_note'] views.py class CommentCreateView(CreateAPIView): # lookup_field = 'no' queryset = Comment.objects.all() serializer_class = CommentCreateSerializer # def form_vaild(self, form): # comment = form.save(commit=False) # comment.writer = self.request.user # comment.board = get_object_or_404(Board, pk=self.kwargs['board_pk']) # return super().form_valid(form) class CommentDeleteView(DestroyAPIView): # lookup_field = 'no' queryset = Comment.objects.all() serializer_class = CommentSerializer urls.py path('boardapi/<int:board_pk>/comment/create/', views.CommentCreateView.as_view(), name='CommentCreateView'), path('boardapi/<int:board_pk>/comment/<int:pk>/delete/', views.CommentDeleteView.as_view(), name='CommentDeleteView'), -
Django TypeError migrate issue
I'm using ubuntu 20.04 and I'm tring using mysql with django I have already installed mysql server and mysqlclinet as well when I type the following command: python3 manage.py migrate but I got the following error Traceback (most recent call last): File "/home/andruxuis/Documents/python/python-testing/mysite/manage.py", line 22, in <module> main() File "/home/andruxuis/Documents/python/python-testing/mysite/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/core/checks/database.py", line 13, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode if not (self.connection.sql_mode & {'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES'}): File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 376, in sql_mode with self.cursor() as cursor: File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/db/backends/base/base.py", line 235, in _cursor self.ensure_connection() File "/home/linuxbrew/.linuxbrew/Cellar/python@3.9/3.9.0_1/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner … -
AWS Lightsail Djanfo Bitnami : Operational Error- Attempt to write read only database
I have a website that is completely functional in development, however, I'm unable to configure the server permissions for my DB.sqlite3 file, so as to allow database changes eg Login, and Register. I'm using the bitnami stack for Django on AWS lightsail and I would appreciate help on the matter. Thanks ! -
Configure SMTP AWS Workmail into Django project
I'm trying to send emails from my Django project. And I want to connect via SMTP with a AWS Workmail. Steps I have done: I already verified the domain I created and tested the mail I want to use, using Workmail I tried the AWS SMTP and it did not worked. But, it works in my cellphone. I tried in the AWS SES, in the "SMTP Settings" and created the "SMTP credentials", with the host and port given, and it didn't worked either. How should I configure it well? I hosted my site in an AWS lightsail instance -
Django Heroku Debug=False only my 404 url works, all other URLs raise Server Error 500
This is quite the opposite of the issues I have seen people run into here. I've been trying to get Debug=False to work for quite some time now. The issue I am running is only my 404.html template is working when Debug=False. All other URLs raise a Server Error (500), even my home page. I've ran a local python manage.py collectstatic and a heroku run python manage.py collecstatic. I am currently running the most recent version of Django. The output for the heroku command is this: 185 static files copied to '/app/staticfiles', 543 post-processed. I have printed my STATIC_ROOT locally and this is it's output: /Users/myname/Desktop/Dev/ProjectFolder/prescottSolar/staticfiles I am not sure if they (the files copied heroku root and my static root) should match 100%? settings.py ALLOWED_HOSTS = [ 'www.example-app-name.com', 'example-app-name.com', 'example-app-name.herokuapp.com', '127.0.0.1', 'localhost' ] MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') print(STATIC_ROOT) MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = AWS_DOMAIN_NAME + '/static/' Here's an example of my urls.py, everything other than the home url has a trailing "/": urlpatterns = [ path('', views.home, name='home'), path('account/', views.account, name='account'), path('contact-us/', views.contact, name='contact'), path('services/', views.services, name='services'), ] Handler (inside of project urls.py … -
How to create a field inside a field in a model in django?
I have model as follows. I have 4 choicefields for people which are (single, couple, family, and group). Users can select any one. But the problem is when the user selects family, he should also select the number of children and no of adults that are going for the trip. Now, how can I have a field in the model such that, I have 4 choices, but for a family choice, I also need an option to select no of adults and no of children. The same goes for group choice. Family pic Single Now my model is: class CustomBooking(models.Model): PEOPLE_CHOICES = ( ('Single', 'Single',), ('Couple', 'Couple',), ('Family', 'Family',), ('Group', 'Group'), ) AGE_GROUP = ( ('18-35 yrs', '18-35 yrs',), ('36-50 yrs', '36-50 yrs',), ('51-64 yrs', '51-64 yrs',), ('65+ yrs', '65+ yrs',), ) people = models.CharField(max_length=64, choices=PEOPLE_CHOICES, default='Couple') geographical_area = models.CharField(max_length=255) bookedfor = models.DateField(blank=True) age_group = models.CharField(max_length=64, choices=AGE_GROUP, default='18-35 yrs') trip_title = models.CharField(max_length=255) description = RichTextField() created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) -
Moving website to Django with existing PostgreSQL DB
I am moving my web application from rails to django, I have successfully connected to my PostgreSQL DB with the django application. My question is, do I have to recreate all of the rails models in django (which will create new database tables) or is there a way to use the existing tables as they are? I am looking through documentation but have not found the specific answer I am looking for. -
New Model in django based in PeriodicTask Model Celery djano beat(overwritting)?
I need to add a new column to the model PeriodicTask from django-celery-beat. So, for that, I try to do a new model which heritages from PeriodicTask model, but I dont know why, It doesnt generate a new table with all the columns(attributes) from the periodictask model. How can I do that? Is it anyway to overwrite or add new columns to models in django? and in django-celery beat? Thanks in advance. -
Python was not found; can be installed from Microsoft store when python is already installed and present in the path
I tried running a Django app both from the VSCode terminal and cmd. But in both cases, I got the error that Python was not found. a) Python is already installed(3.9) & included in the path b) I didn't create a virtual environment c) got the same error when not using Django d) pip is working -
How to get the instance value of a field in a ModelForm?
I have a ModelForm where on first displaying the form, I want to disable one field based on the value of another: class MyForm(forms.ModelForm): field_1 = forms.BooleanField(default=False) field_2 = forms.CharField(default='mytext', required=True) I.e. if field_1 is False, then field_2 will have widget attr disabled. I know I can set the disabled attr on __init__ but how do I look up the value of field_1? E.g: class MyForm(forms.ModelForm): field_1 = forms.BooleanField(default=False) field_2 = forms.CharField(default='mytext', required=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) // If field_1 is False then: self.fields['field_2'].disabled = True I can get the initial value of field_1 with self.fields['field_2'].initial but I want the actual value of the instance. -
How to deal with migration files on docker
Wanted to know what is the proper way of dealing with migration files on djagno docker. Basically, whenever starting a new instance of my docker container, Im always having this error: File "/usr/local/lib/python3.8/site- packages/django/db/migrations/graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration authentication.0001_initial dependencies reference nonexistent parent node ('auth', '0012_userloginactivity') Which arises , i think because of the way my volume syncs up with my local file system.The error goes away when i delete all migration files in my local repo .Therefore how should i structure my project such that i won't encounter such problems in local and in production development? Here is the code to my docker-compose: version: "3.7" services: postgres: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=user - POSTGRES_DB=user networks: - main backend: build: ./backend ports: - "8000:8000" volumes: - ./backend/:/usr/src/backend/ command: python manage.py runserver 0.0.0.0:8000 env_file: - ./.env.dev image: backend-image depends_on: - postgres - redis networks: - main volumes: postgres_data: pgdata: redisdata: networks: main: Here is the docker-compose file for my production: version: "3.7" services: postgres: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=user - POSTGRES_DB=user networks: - main backend: build: ./backend volumes: - static_data:/vol/web/static - media_data:/vol/web/media env_file: - ./.env.dev … -
How do I keep checkbox value checked in django?
Here is models.py class project(models.Model): project_name = models.CharField(max_length = 20) date = models.DateField(("Date"), default=datetime.date.today) user = models.ForeignKey(User, on_delete=models.CASCADE) class check_done(models.Model): checked_value = models.CharField(max_length = 200) current_project = models.ForeignKey(project, on_delete=models.CASCADE) Here is views.py def show(request): log_user = request.user projects = project.objects.filter(user=log_user) return render(request, 'project.html',{'user_project_list':projects}) def checklist(request, project_id): if request.method == "POST": try: current_project = check_done.objects.get(current_project_id = project_id) except: savedata = check_done() savedata.current_project = project.objects.get(id = project_id) savedata.checked_value = request.POST.get('checked_values') savedata.save() return render(request, 'checklist.html') current_project.checked_value = request.POST.get('checked_values') current_project.save() return render(request, 'checklist.html') else: return render(request, 'checklist.html') Here is checklist.html <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function() { $('.chkcvalues').click(function() { var txt = ""; $('.chkcvalues:checked').each(function() { txt+=$(this).val()+"," }); txt =txt.substring(0,txt.length-1); $('#txtvalues').val(txt); }); }); </script> <style> .pcbcheck { width: 800px; margin: auto; text-align: center; } .save { background-color: gray; display: block; margin: 20px 0px 0px 20px; text-align: center; border-radius: 12px; border: 2px solid #366479; padding: 14px 110px; ouline: none; color: white; cursor: pointer; transition: 0.25px; } button:hover { background-color: #4090F5; } .HomeLblPos { position: fixed; right: 10px; top: 25px; cursor: pointer; } </style> </head> <body> <div class="pcbcheck"><h1 style="color:black;font-size:35px;"> PCB Checks</h1></div> <form align="right" method="get"> {% csrf_token %} <label class="HomeLblPos"> <a class="waves-effect waves-light btn green" href="{% url 'show' %}">Home</a> </label> </form> <div class="main"> <form method="POST"> {% … -
Django performance monitoring on AWS
I have a Django app hosted on AWS Lambda (deployed using Zappa tool) an using RDS for hosting the Postgres database. The app is having performance issues with some pages loading very slowly but not others, making me think that the issue is with poorly written data interactions. I remember at work, the devs were using Azure Application Insights which was monitoring apps at a code level. I think the devs had to insert code throughout their apps to get the monitoring, and I think it monitored on a page by page and code line by line basis. Is there any similar tool on AWS which I could use with my App? I appreciate there are much simpler ways of solving my problem but I thought an AWS tool would be something neat to learn. -
How to query for images efficiently from another referencing model in Django
I have these two Django models: class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=10000) class Thumnbnail(models.Model): thumnbnail=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) For an eCommerce website, I want to show list of products, and their multiple thumbnails (a product might have more than one thumbnail!), filtered by product names with a keyword from user input. What is the most efficient way to retrieve all the products and their thumbnails, without querying twice separately for the products and for the thumbnails? I know that using .select_related() we can fetch the foreign objects as well, but it's like I am still missing something. I can either make two separate Serializers, and separate querysets in two Viewsets, in which case I have to do the keyword-name filtering twice, and it definitely doesn't make sense to do it twice, or another way is to make a nested Serializer, with fields from both models, but that is also not a good idea, since the product description will be repeated again and again in every row for every thumbnail that the product has. Omitting the product description field from serializer is also not an option, since I do need to get it at least once. Doesn't make sense to perform another query …