Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framwork POST request gives error of forbidden
I first want to say that yes, I have looked for answers far and wide. This is a very common error. It's a headache and hopefully, there is just a small mistake I've overlooked. Registering a user works, while logging in a user gives: Forbidden: /api/login [17/Nov/2022 19:37:51] "POST /api/login HTTP/1.1" 403 32 From what I'm reading it's all about permissions, but I don't know how to fix it. I'm following this tutorial: https://www.youtube.com/watch?v=PUzgZrS_piQ In settings.py I have for instance: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'posts', 'users', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ] AUTH_USER_MODEL = 'users.User' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True In Views.py I have: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.exceptions import AuthenticationFailed from .serializers import UserSerializer from .models import User #Create your views here. class RegisterView(APIView): def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class LoginView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') return Response(user) Models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): name = models.CharField(max_length=255) email = models.CharField(max_length=255, … -
Encoding error while loading .json django
I have a json file with data from django which I have imported using the command python -Xutf8 ./manage.py dumpdata > data.json And I tried to upload with command python manage.py loaddata data.json gives me an error like File "Z:\Project\Заказы\Murtaza_Filter\backend\manage.py", line 22, in <module> main() File "Z:\Project\Заказы\Murtaza_Filter\backend\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\loaddata.py", line 102, in handle self.loaddata(fixture_labels) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\loaddata.py", line 163, in loaddata self.load_label(fixture_label) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\loaddata.py", line 251, in load_label for obj in objects: File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\serializers\json.py", line 67, in Deserializer stream_or_string = stream_or_string.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte how can i fix this? -
Image Events on Froala Django Editor
I'm using the Froala Django Editor in some forms in my Django REST Framework backend, such as this # resources/forms.py from django import forms from froala_editor.widgets import FroalaEditor from .models import Resource class ResourceForm(forms.ModelForm): class Meta: model = Resource fields = '__all__' widgets = { 'content': FroalaEditor( options={ 'heightMin': 256 } ) } When I try to upload an image (or a video, or any file, but one thing at a time) in the Froala editor I get an error: In the console I have: GET https://{some-id}.cloudfront.net/uploads/froala_editor/images/Nights.of.Cabiria.jpg [HTTP/2 403 Forbidden 15ms] The error above made me wonder that perhaps the image is being uploaded correctly, but the Froala editor can't get it after uploading in order to display it. The application is being hosted in AWS and the uploaded files stored in S3 buckets. And in fact, I checked in the S3 dashboard, and the images are there, so they have uploaded correctly. Even though I'm using all default FROALA_EDITOR_OPTIONS. I'm aware there are specific options for S3 storage (I've tried them) but I'm not using them and it is uploading fine. Still looking at that error, I remembered that in other models in the project I have ImageFields, for … -
django KeyError: 'some-ForeignKey-field-in-model'
I am very badly stuck on this error for days, and I am unable to understand what it is trying to tell me as it is only 2 words. The error is coming when I am trying to insert data into the DB table using python manage.py shell > from app_name.models import Usermanagement > from app_name.models import Inquery i = Inquery( inqueryid=6, inquerynumber="INQ765758499", sourceairportid=Airport(airportid=1), destinationairportid=Airport(airportid=21), stageid=Stage(stageid=1), commoditytypeid=6, customerid=Customer(customerid=1), branchid=1, transactiontype="AGENT", businesstype="Self", hodate="2020-11-18", totalshipmentunits=56, unitid=100, grossweight=100, volumemetricweight=100, remark="test", dateofcreation="2018-11-20 00:00:00", dateofmodification="2018-11-20 00:00:00", createdby = Usermanagement(userid=0), modifiedby = Usermanagement(userid=0)) #error KeyError: 'createdby' #traceback File C:\Python310\lib\site-packages\django\db\models\base.py:768, in Model.save(self, force_insert, force_update, using, update_fields) 757 def save( 758 self, force_insert=False, force_update=False, using=None, update_fields=None 759 ): 760 """ 761 Save the current instance. Override this in a subclass if you want to 762 control the saving process. (...) 766 non-SQL backends), respectively. Normally, they should not be set. 767 """ --> 768 self._prepare_related_fields_for_save(operation_name="save") 770 using = using or router.db_for_write(self.__class__, instance=self) 771 if force_insert and (force_update or update_fields): File C:\Python310\lib\site-packages\django\db\models\base.py:1092, in Model._prepare_related_fields_for_save(self, operation_name, fields) 1087 # If the relationship's pk/to_field was changed, clear the 1088 # cached relationship. 1089 if getattr(obj, field.target_field.attname) != getattr( 1090 self, field.attname 1091 ): -> 1092 field.delete_cached_value(self) 1093 # GenericForeignKeys are private. … -
Django only want to get first row of a queryset
i want to display the first entry of a queryset. i try some answers here but it does´tn work on my code example. here is my code: class FeatureFilmAdmin(admin.ModelAdmin): inlines = [ QuoteAndEffortSetInLine, ProjectCompanySetInLine, VendorVFXSetInLine, VendorSetInLine, StaffListSetInLine, ] list_display = ["title", "program_length", "get_production_company_name"] def get_production_company_name(self, Featurefilm): return FeatureFilm.objects.filter(pk=Featurefilm.id).values( "projectcompanyset__production_company__name" ) so i actually want to display the production_company, from the first table of ProjectCompanySet in the admin as list_display. so i actually want to display the production_company, from the first table of ProjectCompanySet in the admin as list_display. but with the code above, it will show me all production_company, if there are multiple ProjectcompanySet. What is displayed so far is also not the production_company name but the str function and not the data field itself. Here I would need help please. here are the models of my problem: class CompanyOrBranch(CompanyBaseModel): name = models.CharField( "Firma oder Niederlassung", max_length=60, blank=False, ) class FeatureFilm(ProjectBaseModel): class Meta: verbose_name = "Kinofilm" verbose_name_plural = "Kinofilme" class ProjectCompanySet(models.Model): feature = models.ForeignKey( FeatureFilm, on_delete=models.CASCADE, null=True, blank=True, ) production_company = models.ForeignKey( CompanyOrBranch, related_name="production_company", verbose_name="Produktionsfirma", on_delete=models.SET_NULL, blank=True, null=True, ) here is the output of my admin list: -
GetStream (Django) follow doesn't copy activities to the feed
For some reason, neither 'follow' nor 'follow_many' methods can not copy the activities from the targeting feed. I know about the following rules and that's why I double-checked: activities in the target feed were added directly (the target feed doesn't follow any others). That's why I can't find out why the following target feed with activity_copy_limit doesn't copy the specified number of activities. I prepared a quick demo here: from stream_django import feed_manager my_all_feed = feed_manager.get_feed('all', '13344f63-7a47-4e42-bfd0-e1cb7ebc76ad') # this is user's feed (it follows public) activities = len(my_all_feed.get()['results']) # this equals 5 at this point public_feed = feed_manager.get_feed('public', 'all') # this is public feed (general one) public_activities = len(public_feed.get()['results']) # it has 25 activities my_all_feed.unfollow('public', 'all') # I am unfollowing public feed (just to be clean here) activities = len(my_all_feed.get()['results']) # this gives me 0, because I am not keeping history my_all_feed.follow('public', 'all', activity_copy_limit=100) # I am following public feed again (should copy all 25 activities for sure) activities = len(my_all_feed.get()['results']) # and this gives me 5 again, out of 25 I've followed each step in the explorer, so I am sure those results are accurate. And again, the public feed doesn't follow any other feeds, all the activities are … -
I'd like to get feedback on the crypto trading bots architecture(django, celery) [closed]
I want to make crypto trading bots using python, django and celery. But I have no idea how to design architecture. So If you don't mind, Please let me know how to do it. (Sorry for my poor English skills. If there's anything you don't understand, comment me anytime) Requirements Get all of crypto's price every second from openAPI Buy/Sell crypto by comparing between user's average buy price and current price User can see their balance's state by dashboard(django) If the current price exceeds the threshold and the trade process(requirements 2) is executed, the process of receiving crypto price from openAPI(requirements 1) will be delayed. So I planned to separate a process of getting crypto prices from openAPI and storing them in DB. And if the current price exceeds the threshold, the process generates events and delivers them to other processes through a message queue. Also, getting all of the user's average buy price from openAPI every second(requirements 2) can exceed API call limit. So I planned to store user's balance info in DB and synchronize everyday and when buy/sell events occur. I draw architecture with my ideas. I use django for dashboard and celery beat for scheduling, worker for … -
Django: model ForeignKey from a ForeignKey
I want to do something like this en Django: Model1 defines several types. Model2 define a name and select one type. Model3 copy the name and types definited in Model2, and defines other variable. I've tried this, but it doesn't work: class Model1(models.Model): types = models.CharField(max_length=50) class Model2(models.Model): name = models.CharField(max_length=50) types = models.ForeignKey(Model1, on_delete=models.CASCADE, null=True, blank=True) class Model3(models.Model): name = models.ForeignKey(Model2, on_delete=models.CASCADE,related_name='name') types = models.ForeignKey(Model2, on_delete=models.CASCADE,related_name='types') other = models.CharField(max_length=50) This doesn't work. ¿any idea or alternative? Thanks!! -
Django - Annotate queryset with result of function
I am trying to take a queryset and annotate it so that the value of the new field is the result of a function that requires the object being annotated. In this case I am taking a queryset of cars and annotating it with the distance of the car which is calculated by a function. The main issue I am having is getting the annotations to be unique to each car rather than a bulk annotation, I have tried most of the approaches mentioned elsewhere on here but none seem to be working. The closest I have come so far is by using an approach using Unions, this got the annotations in, however my next step is to order this Queryset so I need to have the ability to do that without losing the annotation. For context: car is a Car object, distances is a dictionary of distances. Unannotated is initially set to a queryset of cars which may already have annotation applied from a previous function. The Union solution I found is: for car in unannotated: annotated = unannotated.filter(id=car.id).annotate(distance=Value(get_distance_of_car_from_distances(distances, car))) clean = clean.union(annotated) However as stated previously, this caused issues with the ordering step further on. I have also … -
How to fix no outer ring when creating a project in Django (vscode)?
I have this problem when creating a project in Django (vs code) that only a package <nameoftheproject> gets created and not the outer container (with the same name as the package) that was supposed to be created with the code below. Is this a bug that it is not there or it doesn't appear in the project dir in vscode anymore(course I am doing is from 2018, maybe it doesn't appear anymore)? I could go without it and build an easy application, but I couldn't deploy it using Git and Haroku. This is a source code I used in the terminal to start a project: mkdir vidly cd vidly pipenv install django==2.1 django-admin startproject <nameoftheproject . code . And this is the result enter image description here Is that okay? And if not how do I fix it? Thanks! I tried creating a project in global environment (instead of pipenv). Didn't work. Using different Django version didn't work either. -
django username regex [closed]
django username input allow some symbols with forms.py 'pattern': '[A-z0-9]+[^_]+' not allow _testuser, __testuser, not allow 2 line __ allow test_user, testuser, 'pattern': '[A-z0-9]+[^_]+' i like configure as telegram username -
I write view for my blog and i want after user left a comment web page redirect to that post but i have this problem
Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. return redirect('post_detail', slug=post.slug) This is my comment view: def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day) tags = Tag.objects.all() tagsList = [] for tag in post.tags.get_queryset(): tagsList.append(tag.name) profile = Profile.objects.get(user=request.user) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.profile = profile new_comment.post = post new_comment.save() return redirect('post_detail', slug=post.slug) else: comment_form = CommentForm() post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:3] return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts, 'tagsList': tagsList, 'tags': tags}) Is there anything i missed in redirect function? -
How can I set up a proxy layer for SFTP using Django-storages?
I'm attempting to come up with a solution to my current issue. I have a Django application that enables users to upload files to a remote server with SFTP. This operates without a hitch. I'm having trouble telling the application to download those files from the server after they have been uploaded. I took time to investigate on this subject, but I didn't find much. Although I did find this thread and it was useful, I'm still lacking the final element and how to tie everything together. I created a middleware in my application based on the thread mentioned above, and I made sure to update the middleware in my settings. I'm not sure if the middleware needs to be called somewhere else in the application or some other element needs to be added on top it. Any help is appreciated, thanks. middleware.py import mimetypes from storages.backends.sftpstorage import SFTPStorage from django.http import HttpResponse class SFTPMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): SFS = SFTPStorage() response = self.get_response(request) path = request.get_full_path() if SFS.exists(path): file = SFS._read(path) type, encoding = mimetypes.guess_type(path) response = HttpResponse(file, content_type=type) response['Content-Disposition'] = u'attachment; filename="{filename}"'.format(filename=path) return response settings.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", … -
Django + FastAPI
Can i run FastAPI server when i put in terminal python manage.py runserver. I want -> when django server is already running he also run server for fastapi, so then i can do something like that in browser ('api/' -> give me FastAPI), but when ('django/'-> give me django -> root page my project). In general, I want to make access to the api through some path, as well as a full-fledged Django site that will use this api for its purposes, with templates, etc. And so that the user can switch between them at any time -
Python can't find MySQL ... why not?
Here is the complete traceback: (MacOS) Traceback (most recent call last): File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so, 0x0002): Library not loaded: '@rpath/libmysqlclient.21.dylib' Referenced from: '/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so' Reason: tried: '/usr/lib/libmysqlclient.21.dylib' (no such file) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): … -
Problem with implementation of django-microsoft-auth in Django app with custom user model
I want to implement django-microsoft-auth library to my Django project and I am struggling with migrating data. The problem is that I am using Custom User model that does not contain a username field and when I am trying to run the foolowing command: python manage.py migrate I get error like this: SystemCheckError: System check identified some issues: ERRORS: <class 'microsoft_auth.admin.UserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'user.User'. I've cloned the repository and I don't see anywhere in admin.py or in any other file that ordering is refering to a username field. My user model looks like this: class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" … -
Error trying to migrate my database. Typing error
Sorry but I don't know what is happening when I try to run (python3 manage.py makemigrations) I really don't know what's going on I'm looking for an answer for a while but I can't figure out where the error is (paginas) root@janstar:/home/paginas/proyectodedjango# python3 manage.py makemigrations Traceback (most recent call last): File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations if self.has_table(): File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 260, in cursor return self._cursor() File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 236, in _cursor self.ensure_connection() File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 199, in get_new_connection conn = Database.connect(**conn_params) TypeError: argument 1 must be str, not PosixPath During handling of the … -
Django not connecting to postgres db. port 5432 failed: FATAL: database "postgres" does not exist
I have a database called postgres. However when trying to connect it gives the following error output: port 5432 failed: FATAL: database "postgres" does not exist. If i change to template1 it works but i want to use postgres. Please see image of list of db's Django settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Please note i am using Docker. docker-compose.yml services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres -
How to set the title of a new tab when returning a fileresponse
I have an button that when pressed opens up a new tab and displays a PDF. When the new tab is opened the title looks like some sort of metadata about the PDF. ex: "Microsoft Powerpoint:The original.ppt" instead of the name of the PDF "Generated.pdf". How do I set the title of the tab to be the name of the actual PDF being displayed? <input type="button" onclick="window.open('{% url 'get_file' %}','_blank');" value="Show File"/></td> views.py: def GetFile(request) filepath = os.path.join('my_path/' + variable + '/' + filename) response = FileResponse(open(filepath, 'rb'), content_type='application/pdf') response['Content-Disposition'] = 'filename="{}"'.format(filename) return response -
How to use arrays in loop with if statment in django template
I want to choose include button_free when hour_1 is 0 or choose button_busy when hour_0 is 1 view def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[hour_1] = [0,0,1,1,0] context['range_5'] = [0, 1, 2, 3, 4] return context ` part of template {% for schedule_part in range_5 %} {% if hour_1.schedule_part == 0 %} {% include "users/button_free.html" with button_id=hour_1.schedule_part %} {% else %} {% include "users/button_busy.html" with button_id=hour_1.schedule_part %} {% endif %} {% endfor %} hour_1 is for example [0,0,1,1,0] Displays only button_busy When debugging hour_1.schedule_par raises VariableDoesNotExist exception. How should I get to the hour_1 elements -
Django - Python: Shopping bag for theatre tickets. Ticket models for two separate prices (adult_price/ child_price)
I am setting up a Django project to allow tickets to be sold for various theatre dates with a price for adults and a price for children. I have created a models.py and ticket_details.html. I am unfortunately receiving the error: 'int' object has no attribute 'get' and I am at a loss to how I am to get the adult and child price for the total calculations to display in my bag.html. The problem is with my contexts.py and views.py files. I have tried the 'get' option but it is not working. Can someone advise? enter image description here models.py: class Show(models.Model): '''Programmatic Name''' name = models.CharField(max_length=254) friendly_name = models.CharField(max_length=254, null=True, blank=True) poster = models.ImageField(null=True, blank=True) def __str__(self): return self.name def get_friendly_name(self): return self.friendly_name class Ticket(models.Model): show = models.ForeignKey('show', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=254) event_date = models.CharField(max_length=254) description = models.TextField(null=True, blank=True) event_details = models.TextField(null=True, blank=True) place = models.CharField(max_length=254) location = models.CharField(max_length=254) position = models.CharField(max_length=254) image = models.ImageField(null=True, blank=True) price_details = models.TextField(null=True, blank=True) date = models.DateTimeField(null=True, blank=True) adult_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) child_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) def __str__(self): return self.name ticket_detail.html: <form class="form" action="{% url 'add_to_bag' ticket.id %}" method="POST"> {% csrf_token %} <div class="form-row"> <div class="form-group w-50"> … -
How to optimize multi column indexing in Django with PostgreSQL
In my application I have this model: class ObservedData(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) unique_id = models.CharField(max_length=128) timestamp = models.DateTimeField() value = models.FloatField(null=True) 90% of my queries are select * from ObservedData where user=<user> AND unique_id=<uid> AND timestamp BETWEEN <date1> AND <date2> This is how I am indexing: class Meta: indexes = [ models.Index(fields=['user', 'unique_id', 'timestamp']), models.Index(fields=['user', 'unique_id']), models.Index(fields=['unique_id', 'timestamp']), ] unique_together = ('user', 'unique_id', 'timestamp') Is this the correct way to do it? I have noticed an increased growth of the database allocated space and I was wondering if this is an overloading or unnecessary overlapping of indexes. -
RetrieveUpdateDestroyAPIView image field when i update a field in django rest framework
i created this api which has a model collection where there is an image field. the list and collection creation part is not a problem but the part of detail especially update has a problem, when I want to update a field I get an error because the image field is not filled in. How can I fix this, I would like if I don't change the image the file will remain the same. model class Collection(models.Model): name = models.CharField(max_length = 255) description = models.TextField() discount = models.PositiveIntegerField(default = 0) image = models.ImageField(upload_to ='collection/') active = models.BooleanField(default = False) def __str__(self): return self.name serializer class CollectionSerializer(serializers.ModelSerializer): class Meta: model = Collection fields = ('id', 'name', 'description', 'discount', 'image', 'active') views class CollectionDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Collection.objects.all() serializer_class = CollectionSerializer url path('collections/', CollectionListCreate.as_view(), name="collections-list"), path('collections/<int:pk>/', CollectionDetail.as_view(), name="collection-detail"), -
DJANGO: How to Display or Access Data from ListView and DetailView on The Same Page / Template?
I want to be able to render, display or access List-view and Detail-view on this same page or Django templates. Below is what I tried so far. Here is a link to where I got a very similar but limited code on how to solve this issue. (DJANGO: How to access data from ListView and DetailView on the same template?). The result when I runserver.py shows a completely blank page with no single error even on the terminal Please Help me resolve this issue. THANKS A LOT models.py class Reports(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=255) name = models.CharField(max_length=255) email = models.EmailField(max_length = 254) phone = models.CharField(max_length=11) address = models.CharField(max_length=255, blank=True, null=True) subject = models.CharField(max_length=255) message = models.TextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) due = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ('-created',) views.py from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.views.generic.list import ListView from django.views.generic.detail import DetailView from datetime import timezone, tzinfo from . models import Reports # Create your views here. class index(TemplateView): template_name = 'reports_list.html' class ReportsListView(ListView): model = Reports # context_object_name = 'data' def get_queryset(self): return Reports.objects.filter(create_date__lte=timezone.now()).order_by('-create_date') class Detail(DetailView): model = Reports def get_context_data(self, **kwargs): context … -
Django postgres psycopg2: ImproperlyConfigure even though module installed
I am using Django for the first time but have used PostgreSQL previously. I am trying to follow the official Django tutorial to set up with a database. I have followed everything but I get an error when using the command "python manage.py migrate" that psycopg2 is not found even though I have it installed.Traceback (most recent call last): File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/alexanderverheecke/Documents/GitHub/mysite/manage.py", line 22, in <module> main() File "/Users/alexanderverheecke/Documents/GitHub/mysite/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import …