Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django Lightsail - attempt to write a readonly database
for a few days now I have been trying to deploy my Djago app on AWS Lightsail, and it's just one problem after another. The frustration levels are over the roof. This time, when I try to login/register, I am getting this error: Attempt to write a readonly database I have been googling solutions for quite some time and have tried setting different permissions, even giving away all permissions which might be huge security risk, however it still doesn't work. Could anyone help me. Thank you -
Django Rest Framework: how to access single API elements in URL?
I want to access every API element by URL like this "/api/v1/element_id" I have explicitly defined the pk in serializers serializers.py class TweetSerializer(serializers.ModelSerializer): tweet_id = serializers.IntegerField() class Meta: fields = ('tweet_id', 'author', 'text', 'created_at', 'retweet_count', 'favourite_count',) model = Tweet But it does not work. I get Not found error models.py class Tweet(models.Model): #tweet_id = models.ForeignKey(User, on_delete=models.CASCADE) tweet_id = models.IntegerField() created_at = models.CharField(max_length=100) text = models.TextField() author = models.CharField(max_length=100) retweet_count = models.IntegerField() favourite_count = models.IntegerField() def __str__(self): return str(self.tweet_id) views.py class TweetList(generics.ListCreateAPIView): queryset = Tweet.objects.all() serializer_class = TweetSerializer class TweetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Tweet.objects.all() serializer_class = TweetSerializer urls.py urlpatterns = [ path('<int:pk>/', TweetDetail.as_view()), path('', TweetList.as_view()), ] Listing all tweets works fine, /api/v1/, but single tweet is not returned. I have tried to set a ForeignKey in the models but then I get an error column tweet_id_id not found. -
Django FileField and Media config
I'm completely stuck with this, I have a simple Model with a File-Field: class EmailTemplate(models.Model): template_name = models.CharField(max_length=100, primary_key=True, verbose_name='Template Name') template_file = models.FileField(upload_to=f'documents/non_voice/email_templates', verbose_name='File', validators=[validate_txt_extension]) def __str__(self): return self.template_name The User is able to upload a file through a form and should be able to download them as reference later on. Upload works like a charm but when I present the file in a django_table - Table it links to it's relative path and download won't work since it tries to serve only the partial file path. Shouldn't Django automatically pre-pend my Media Dir to build the correct path?? (I can't provide a full path as "upload_to" only accepts relative ones!) Also the standard upload widget is showing it's current path as a link which is also not working when you click on it, so I would assume the issue has to be somewhere else (best guess is my media settings...) My Media Settings look like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') LOG_DIR = os.path.join(BASE_DIR, 'logs') # MEDIA MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' Any ideas? -
Tus JS Client file upload without CSRF in Django
I want to upload a large video file using tus-js-client to my django media directory. I am encountering a csrf token 403 error. How can I the crsf token to the tus POST and PUT/PATCH requests. See my code below let video_file = $('#id_video_file')[0].files[0]; let tus_uploader = new tus.Upload(video_file, { endpoint: 'http://127.0.0.1:8000/media/myfolder/', retryDelays: [0, 1000, 3000, 5000, 10000], metadata:{ filename: video_file.name, filetype: video_file.type, }, uploadSize: video_file.size, onError: function (error) { }, onProgress: function (bytesUploaded, bytesTotal) { let percentage = (bytesUploaded/bytesTotal * 100).toFixed(2); console.log(percentage); }, onSuccess: function () { console.log("Download %s from %s", tus_uploader.file.name, tus_uploader.url) } }); tus_uploader.start(); -
How do I use django formset_factories?
I am trying to work on a django-based project/website that logs who took out our dogs last. I am very new to django so please bear with lack of knowledge in the field. I currently have my project set up so that I have models based on users/family members, the families' dogs, posts (logs of when and who took out the dogs), and actions, which is a child class that uses the dog and post models as foreign keys to see if the dogs peed and or pooped when they were taken out. The part that I am stuck on is trying to figure out how I create the post form. Since we have two dogs I need the form/post page to display a set of check boxes (for peeing and pooping actions) for each dog model that exists. While I can successfully display one action set, I run into the difficulty of trying to display the correct number of action sets and also to post the set of actions and the post itself. I have been trying to work with the formset_factory function but I am confused as to how I get it to function properly. Can anyone help? … -
temporarily adding watermark image/copyright text while displaying image in django template
I am creating a stock photo site. I need to add watermark temporarily while displaying in django template so that user shouldn't be able to download original photo without purchasing. I've tried django-watermark but got error while migrating. python 3.8+ and django 3.1.3+ So far I've overlapped images using this code, water_mark_image = Image.open(settings.MEDIA_ROOT+'/water.png') water_mark_image = wat.resize((int(im.width/2), int((im.width/2)*(h/w)))) Original_image.paste(wat, (int((im.width-wat.width)/2), int((im.height-wat.height)/1)), mask=wat) but while downloading image comes along with watermark. I dont want to save duplicate image. Please suggest me a way to add watermark temporarily while displaying in detail.