Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Most efficient way to paint columns in django template / view
I have an app where I allow the users to create a customized dashboard containing 'widgets'. They can choose 1,2 or 3 columns and then select widget column and widget order. The widgets will be of differing heights so have to paint in columns rather than rows. I loop through the widgets and annotate with a colno and then send this to the template. during initial dev I've just looped through them all in the template and am now looking to make this a little more efficient. I would expect between 15-20 widgets per page. in the template at the moment I have: <div class="column"> {% for widget in widgets %} {% if widget.colno == 1 %} {% include 'widget.html' %} {% endif %} {% endfor %} </div> <div class="column"> {% for widget in widgets %} {% if widget.colno == 2 %} {% include 'widget.html' %} {% endif %} {% endfor %} </div> <div class="column"> etc </div> Obviously not the most efficient way to do this. Wondering if there are better ways that this could be done: a) Iterate through in the view and assign widgets to dictionaries based on their colno. Then iterate through these in the template. - … -
Can a localhost address be allowed to load a site in an iframe from the csp header?
I would like to know if it is possible to allow localhost to make changes to a specific site by setting it in the csp header in the settings.py file of the Django project. For my part, I am trying to load my Django site in an iframe present on a page at the following address http://localhost:3000/searchEngine. So I inserted this in my settings.py file: CSP_FRAME_ANCESTORS = ("'self'", 'localhost:*') This is taken into account, but still does not allow localhost to load the site in the iframe and I get the following error, when I try to load this site in the iframe: Refused to frame 'https://gkwhelps.herokuapp.com/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self' localhost:*". I don't know not why yet I did not make syntax errors. So I wonder if django-csp takes localhost into account. I would like to allow my site to load in an iframe from any port in my localhost. -
How to check how much session expiry time is left? (Django)
With "views.py" as shown below, I'm trying to check how much session expiry time is left by setting "60" seconds expiry time but after "20" seconds sleep, get_expiry_age(), get_session_cookie_age() and get_expiry_date() didn't return "40" seconds expiry time which is expected: # "views.py" from django.shortcuts import render import time def test(request): request.session.set_expiry(60) # "60" seconds expiry time is set time.sleep(20) # Sleep for "20" seconds print(request.session.get_expiry_age()) # 60 print(request.session.get_session_cookie_age()) # 1209600 print(request.session.get_expiry_date()) # 2022-08-07 00:34:41.700828+00:00 return render(request, 'test/index.html') So, are there any ways to check how much session expiry time is left? -
Dockerizing Django - Unable to visit running localhost
Dockerfile: FROM python:3.9-alpine WORKDIR /app ENV PYTHONUNBUFFERED=1 COPY /drf/ . RUN pip install -r requirements.txt CMD ["python", "manage.py", "runserver"] When I build an image from this Dockerfile and try to run it, it seems to be running successfully (after running docker run <image> I get these logs): Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 07, 2022 - 00:42:33 Django version 4.1, using settings 'drf.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. The problem is when I try to visit http://127.0.0.1:8000/ it cannot be reached (This site can’t be reached). What might be the issue? I guess I have to play with ports in my Dockerfile. Thanks in advance! -
many to many relation in a dynamic url
i have this model shema: class A(Models.model): related = models.ManyToManyField("self", null=True) and if i retrieve data from the database like this: >>> result = A.objects.filter(pk=1) >>> result.values('related__id') [{'id': 2}, {'id': 3}] >>> result.values_list('related__id') [(2,), (3,)] >>> result.values_list('related__id', flat=True) [2, 3] how do i put the 2 and 3 in mine url, so for eaxpmle, i have this url: path('relationships/<related_id>/<related_id>/<related_id>', views.relationships.edit), so when i press a button it will give me this url: 'relationships/1/2/3' and when i press again it will given me this url 'relationships/2/3/4' ```somone has an idea? -
How to execute Django dispatched signal in view function?
Info: I want to make app like upload file before submit the form. TusUpload will receive the file data and send signal. if user add multiple files it will send signal multiple time. I want to execute this signal in create_page the Example code is in the below. The create_page function take the files which files signals send by TusUpload and saved into the Attach model object post object also linked. The create_page is just a logic which i want to perform. I hope you will be able to provide the information. views.py class TusUpload(View): def patch(self, request, resource_id, *args, **kwargs): tus_file = TusFile.get_tusfile_or_404(str(resource_id)) chunk = TusChunk(request) if tus_file.is_complete(): # file transfer complete, rename from resource id to actual filename self.send_signal(tus_file) return TusResponse(status=204, extra_headers={'Upload-Offset': tus_file.offset}) def send_signal(self, tus_file): tus_upload_finished_signal.send( sender=self.__class__, metadata=tus_file.metadata, file_id=tus_file.resource_id, filename=tus_file.filename, upload_file_path=tus_file.get_path(), file_size=tus_file.file_size, upload_url=settings.TUS_UPLOAD_URL, destination_folder=settings.TUS_DESTINATION_DIR) signals.py tus_upload_finished_signal = django.dispatch.Signal( providing_args=[ "metadata", "file_id", "filename", "upload_file_path", "file_size", "upload_url", "destination_folder" ] ) views.py def create_page(request): files = [] @receiver(tus_upload_finished_signal) def create_file(sender, **kwargs): filename = kwargs['filename'] files.append(filename) if request.method == 'POST': form = PostForm(request.POST or None, request.FILES) if form.is_valid(): form.save(commit=False) form.instance.author = request.user form.save() for f in files: attach = Attach() attach.file = f attach.post=form.instance attach.save() return redirect('index_page') else: form = PostForm() … -
Django and Golang hosting
I'm just here to ask a few questions. I am not asking for hosting provider advice or anything of the sort. Some information; I have 2 servers, and no load balancer. I host my Django instance on server 1 I host my staticfiles and media on server 2, using a golang webserver. Server 2 hosts files trailing with /static/ and /media/ (Django does not use these URLS) What I want to do however, is run the two instances, basically side by side using the same URL. So the URLs would kind of look like this (example): ('/', django) ('/*', django) ('/static/*', GOLANG static server) ('/media/*', GOLANG static server) CDN's are not an option, unfortunately. Redirects are not an option. I need to host everything from a single instance. This means one ip address, one protocol, one server. -> Instead of django serving all staticfiles, django neglects the request, and just gives up hosting -> Golang server takes over, serves staticfiles, returns control. I have two servers (machines) to my disposal, but if using just one of the two takes away a lot of complexity, it is acceptable. I do not need to use both machines. So if it is possible … -
Django display Date in input box
I have an program that allows to save information about an expense. I currently trying to implement a settings option to set a range of dates. At this very moment, Django and Jinja by default, show the date format as m/d/y but I would like it to be d/m/y. The form properly displays the date that is already saved to the page from the database. forms.py class SettingsForm(forms.ModelForm): start_date = forms.DateField( label='', widget=DateInput( attrs={ 'class': 'form-control', 'style': 'width: 200px;', }, ), initial=date(date.today().year, date.today().month, 1) ) end_date = forms.DateField( label='', widget=DateInput( attrs={ 'class': 'form-control', 'style': 'width: 200px;', }, ), initial=date(date.today().year, date.today().month, 28) ) class Meta: model = Settings fields = [ 'start_date', 'end_date' ] widgets = { 'start_date': DateInput(), 'end_date': DateInput(), } And it displays like this: Saved date wrong format If I add the format in the widget. widget=DateInput( attrs={ 'class': 'form-control', 'style': 'width: 200px;', }, format='%d/%m/%Y' ) Ends up like this: No date, format was not applied Erases the value stored in the database and does not do the job because format it's still m/d/y. How can I keep the date from the database and format it to d/m/y? -
how does unit testing works in django? (with coverage)
i am finding it kinda confusing to do unit testing especially with fields that has blank=True attribute or unique=True look at this for example: class TagTest(TestCase): def create(self): tag = models.Tag.objects.create(name='test') return tag def test_get(self): tag = self.create() self.assertIsInstance(tag, models.Tag) self.assertEqual(tag.name, tag.__str__()) self.assertEqual(len(tag.name),4)class TagTest(TestCase): def create(self): tag = models.Tag.objects.create(name='test') return tag def test_get(self): tag = self.create() self.assertIsInstance(tag, models.Tag) self.assertEqual(tag.name, tag.__str__()) self.assertEqual(len(tag.name),4) look at coverage for example, it is telling me i am not covering the test case at all -
How any web hosting site protect files from deleting?
I am creating a python code testing (pytest) website using django and deploy on azure and I just test a code and try to delete files in the root directory of my project using shutil.rmtree() but It returns code like this ============================= test session starts ============================== platform linux -- Python 3.9.7, pytest-7.1.2, pluggy-1.0.0 rootdir: /tmp/8da77f5e80b846d collected 1 item codes/test_with_pytest.py F [100%] =================================== FAILURES =================================== _______________________________ test_check_test ________________________________ def test_check_test(): from .code import check_test > assert check_test() == 90 /tmp/8da77f5e80b846d/codes/test_with_pytest.py:3: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /tmp/8da77f5e80b846d/codes/code.py:7: in check_test shutil.rmtree('/') /opt/python/3.9.7/lib/python3.9/shutil.py:726: in rmtree _rmtree_safe_fd(fd, path, onerror) /opt/python/3.9.7/lib/python3.9/shutil.py:663: in _rmtree_safe_fd _rmtree_safe_fd(dirfd, fullname, onerror) /opt/python/3.9.7/lib/python3.9/shutil.py:663: in _rmtree_safe_fd _rmtree_safe_fd(dirfd, fullname, onerror) /opt/python/3.9.7/lib/python3.9/shutil.py:663: in _rmtree_safe_fd _rmtree_safe_fd(dirfd, fullname, onerror) /opt/python/3.9.7/lib/python3.9/shutil.py:663: in _rmtree_safe_fd _rmtree_safe_fd(dirfd, fullname, onerror) /opt/python/3.9.7/lib/python3.9/shutil.py:683: in _rmtree_safe_fd onerror(os.unlink, fullname, sys.exc_info()) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ topfd … -
Django Admin: How to merge items with same name to simplify view
Big Django newbie here. I have an admin view grouping items like this, tho as the number of bids grows it would be tiresome for one to scroll down all the items, so I wanted to group them by the item names that once clicked would show the columns 'bidder' and 'value'. The Admin page: https://i.imgur.com/VOjrlQZ.png I was looking into aggregate and annotate to merge them. Am I looking for the right thing? The model in question is this: class Bid(models.Model): item = models.ForeignKey(Auction_Listing, on_delete=models.CASCADE, related_name='items', related_query_name='item') bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bidders', related_query_name='bidder') value = models.DecimalField(max_digits=10, decimal_places=2, default=0) def __str__(self): return f"{self.item}" In the Admin I got: class BidAdmin(admin.ModelAdmin): list_display = ('item', 'bidder', 'value') def get_queryset(self, request): queryset = super(BidAdmin, self).get_queryset(request).order_by('item') return queryset Any help appreciated! -
How to use return redirect as a callback function in Django
I have been trying to get my code working through out the whole day. I have a view function but its too verbose plus i am trying to use its implementation on another view so i am trying to refactor the code for the function to be able to run in another view. Have been able to get the function to work except for the fact that there is a return redirect with the profile name within the function(its just a plain function and not a view function). Everytime i try to run the code by passing the redirect as a call back function it always produces an HttpRedirectError and also displays the location of the object in memory, how can i go about using the return redirect as a callback or whichever way i can get it working with my code. The Function code: def foo(filter,images,request,redirector): #do something return redirect(redirector) The View Code: if something: foo(filter,images,request,'home') For the View have also tried: def redirector(): return 'home' foo(property,images,request,redirector) Is there any way i can get this to work, if i don't get it to work, would have to repeat unecessary codes for another function. -
Cant make Django execute only one query with multiple joins using .all()... or even .raw(sql) methods
I'm new to Django and wanted to give it a try to convert an already existing PHP application to Django. But I'm already stuck creating a queryset over multiple joined tables so only one sql query would be executed. I'm using a MySql DB. I already managed to create a view that reduces the amount of queries with .all(), .filter, .order_by and multiple .select_related but couldn't get it to make only one sql query call. So I thought I should maybe use the .raw(sql) method, but even using this approach made Django execute hundrets of single sql queries not respecting the joins. Maybe you could help me a bit getting this, normally simple thing, to work in Django? Here's my original SQL query which works absolutely fine if run in MySql and gives a nice resultset: SELECT `hosts`.`id`, `hosts`.`hostname`, `domains`.`domain_name`, `hosts`.`description`, `hosts`.`installation_by_company_id`, `hosts`.`care_by_company_id`, `hosts`.`system_care_by_department_id`, `hosts`.`system_care_accounting_type_id`, `os`.`operatingsystem`, `os`.`lsbdistcodename`, `os`.`lsbdistrelease`, `os`.`lsbmajdistrelease`, `system_care_department`.`department_name` AS `system_care_department`, `additional_software_care_department`.`department_name` AS `additional_software_care_department`, `system_installation_company`.`company_name` AS `system_installation_company`, `system_installation_company`.`company_abrebreation` AS `system_installation_company_abrebreation` FROM `hosts` JOIN `domains` ON `hosts`.`domain_id` = `domains`.`id` JOIN `hosts_fix_data_scans` ON `hosts_fix_data_scans`.`host_id` = `hosts`.`id` JOIN `os` ON `os`.`id` = `hosts_fix_data_scans`.`os_id` JOIN `companies_departments` ON `companies_departments`.`id` = `hosts`.`system_care_by_department_id` JOIN `companies_departments` AS `system_care_department` ON `system_care_department`.`id` = `hosts`.`system_care_by_department_id` JOIN `companies_departments` AS `additional_software_care_department` ON … -
Django served with apache: how to set PYTHONPATH?
I have a Django app that works fine when served with the command "python manage.py runserver". Now I want to have the app served by Apache and got some issues. One issue is that somehow I can't not set PYTHONPATH. I tried either of the following two ways to set it in a apache conf file: WSGIPythonHome /data/anaconda3/envs/partsdb WSGIPythonPath /data/partsdb/partsdb or WSGIDaemonProcess partsdb python-home=/data/anaconda3/envs/partsdb python-path=/data/partsdb/partsdb But I got errors saying PYTHONPATH = (not set). Below is the whole error message from the apache server. Current thread 0x00007fb4880ad940 (most recent call first): <no Python frame> Python path configuration: PYTHONHOME = '/data/anaconda3/envs/partsdb' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/data/anaconda3/envs/partsdb' sys.base_exec_prefix = '/data/anaconda3/envs/partsdb' sys.platlibdir = 'lib64' sys.executable = '/usr/bin/python3' sys.prefix = '/data/anaconda3/envs/partsdb' sys.exec_prefix = '/data/anaconda3/envs/partsdb' sys.path = [ '/data/anaconda3/envs/partsdb/lib64/python38.zip', '/data/anaconda3/envs/partsdb/lib64/python3.8', '/data/anaconda3/envs/partsdb/lib64/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' When I ran python (both /usr/bin/python3 and /data/anaconda3/envs/partsdb/bin/python3) from the commandline, I didn't get errors from the code import encodings. The apache server kept running and … -
Why is the code creating an empty object in Django Rest Framework
For some reason, when I send my data from my frontend, the backend will create an empty objects. models.py class Workout(models.Model): GOALS_CHOICES = ( ('None', 'None'), ('Abs', 'Abs'), ('Arms', 'Arms'), ('Cardio', 'Cardio'), ('Core', 'Core'), ('Endurance', 'Endurance'), ('Flexibility', 'Flexibility'), ('Full Body', 'Full Body'), ('Legs', 'Legs'), ('Lower Body', 'Lower Body'), ('Power', 'Power'), ('Shoulders', 'Shoulders'), ('Sport Conditioning', 'Sport Conditioning'), ('Stability', 'Stability'), ('Strength', 'Strength'), ('Toning', 'Toning'), ('Upper Body', 'Upper Body'), ('Weight Loss', 'Weight Loss') ) exercises = models.ManyToManyField(Exercise, through='Targets') name = models.CharField(max_length=200, blank=True) profile = models.ForeignKey(Profile, on_delete=SET_NULL,null=True, blank=True) description = models.TextField(max_length=3000, blank=True) goals = models.CharField(max_length=25, choices=GOALS_CHOICES, default='None') workout_time = models.CharField(max_length=200, blank=True) difficulty = models.CharField(max_length=10,blank=True) status = models.CharField(max_length=15, default='Created') created = models.DateField(auto_now_add=timezone.now()) assigned = models.DateField(blank=True, null=True) completed = models.DateField(blank=True, null=True) time = models.CharField(max_length=100, blank=True, null=True) rating = models.IntegerField(default=0, blank=True, null=True, validators=[MaxValueValidator(5), MinValueValidator(0)]) overall_notes = models.TextField(max_length=3000, blank=True) favorited = models.CharField(max_length=1, null=True, blank=True) def __str__(self): return self.name serializers.py class WorkoutSerializer(serializers.ModelSerializer): """Serializer for workout objects""" class Meta: model = Workout fields = ['id', 'name', 'description', 'goals', 'workout_time', 'difficulty', 'status', 'created', 'assigned', 'completed', 'rating', 'overall_notes', 'favorited'] read_only_fields = ('id',) views.py class WorkoutListCreateAPIView(generics.ListCreateAPIView): queryset = Workout.objects.all().order_by('assigned').order_by('completed') serializer_class = WorkoutSerializer Why is my code creating empty objects. I've tested through Postman, and was able to create said object. Suggestions? -
Cannot resolve keyword into field. Choices are following, in Django
I have the following models, models.py class Account(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True) profile_pic = models.ImageField(null=True, blank=True) ratings = models.FloatField(default=1000) date_joined = models.DateTimeField(auto_now_add=True, null=True) phone = models.CharField(max_length=255, null=True) class Match(models.Model): match_time = models.DateTimeField(null=True) totalPlayers = models.IntegerField(default=2) winner = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) class Meta: ordering = ['-match_time'] class Participant(models.Model): match = models.ForeignKey(Match, on_delete=models.CASCADE) player = models.ForeignKey(Account, on_delete=models.CASCADE) player_points = models.FloatField(null=True) What I want is basically to write a Query that can return me the following things, Player_Name, Total Matches by Player, Total Points of Player, Matches Won by the Player, Player Ratings I wrote a query like this and it worked great for all the columns above, except Total Points of Player and Matches Won by the Player players = Account.objects.annotate(matches=Count('participant')).order_by('-ratings') So, following the same principle, I tried the following Query to get what I needed exactly, players = Account.objects.annotate(matches=Count('participant'), total_points=Count('player_points'), matches_won=Count('winner')).order_by('-ratings') But this is giving me the following error, Cannot resolve keyword 'player_points' into field. Choices are: date_joined, id, match, matches, name, participant, phone, profile_pic, ratings, user, user_id I unfortunately do not understand how I can get my required result. Can anyone help me reach what I am trying to do? -
Django - How to annotate with count of related model items
I have these models: class Gym(models.Model): name = models.CharField() class Employee(models.Model): name = models.CharField() gym = models.ForeignKey(Gym) class Appointment(models.Model): time = models.DateTimeField() gym = models.ForeignKey(Gym) class AppointmentItem: name = models.CharField() employee = models.ForeignKey(Employee) appointment = models.ForeignKey(Appointment) I want to get a list of salon employees by appointment item count. How can I do this? -
How can i store the Django view class response into other function and execute it into next one function?
Info: I want to make app like upload file before submit the form. I am upload the files using uppy which is a front-end library. TusUpload will receive the file data and store in Library model. I want to get the uploaded files into the another view function for attach these uploaded files with other Model object. I mean, i want to store the TusUpload response in anther function and then create_page will take these uploaded files before submit the form and then submit it with the Post model object. I know the ajax will store the TusUpload response and then we pass these files ID's in 'create_pagebut i don't want to use this method. I want to pass these filesID's` in backend Not with javascript. I hope you will be able to provide the information. class TusUpload(View): def post(self, request, *args, **kwargs): metadata = self.get_metadata(request) metadata["filename"] = self.validate_filename(metadata) message_id = request.META.get("HTTP_MESSAGE_ID") if message_id: metadata["message_id"] = base64.b64decode(message_id) file_size = int(request.META.get("HTTP_UPLOAD_LENGTH", "0")) tus_file = TusFile.create_initial_file(metadata, file_size) return TusResponse( status=201, extra_headers={'Location': '{}{}'.format(request.build_absolute_uri(), tus_file.resource_id)}) def head(self, request, resource_id): tus_file = TusFile.get_tusfile_or_404(str(resource_id)) return TusResponse( status=200, extra_headers={ 'Upload-Offset': tus_file.offset, 'Upload-Length': tus_file.file_size, }) def patch(self, request, resource_id, *args, **kwargs): tus_file = TusFile.get_tusfile_or_404(str(resource_id)) chunk = TusChunk(request) if … -
Django File upload looping
How would I best loop a form like this (there is other code in the form but this is an example for image uploading) <form action="{% url "upload" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="image_file"> <input type="file" name="image_file2"> <input type="file" name="image_file3"> <input type="file" name="image_file4"> <input type="file" name="image_file5"> <input type="submit" value="submit" /> </form> for single file uploading but need it multifile uploading: def image_upload(request): if request.method == "POST" and request.FILES["image_file"]: image_file = request.FILES["image_file"] fs = FileSystemStorage() filename = fs.save(image_file.name, image_file) image_url = fs.url(filename) print(image_url) return render(request, "upload.html", { "image_url": image_url }) return render(request, "upload.html") Just not sure how to loop it so images are stored along with filename in a var for the db (at a later point) also just a thought, might not always be uploading all five files could be three or none -
Filter the data based on best time to visit the place using Django
Hey guys I am working on a Django project! I have a bootstrap form where the users can fill out the starting and ending dates of their travel. I need to filter the data if the dates fall under the specified month's range in my Django model. I tried to simulate one but it's not filtering the data.. can someone help me out with this? The code for the same is pasted below. The following is the code for my models.py, views.py, and tourform.html respectively! For example, the best time to visit an Amusement park is during the summer so I'll be storing the starting_month in a Django field of the tour model and the ending month in the end_month field of the model. Whenever a user tries to submit the form I'll slice the month from the starting and ending dates entered by the user and I need to filter all those places which are best to visit during those specified months based on the start and end month field present in the database. models.py start_month_choices=[('1','January'),('2','February'),('3','March'),('4','April'),('5','May'),('6','June'),('7','July'),('8','August'),('9','September'),('10','October'),('11','November'),('12','December')] end_month_choices=[('1','January'),('2','February'),('3','March'),('4','April'),('5','May'),('6','June'),('7','July'),('8','August'),('9','September'),('10','October'),('11','November'),('12','December')] start_month=models.CharField(max_length=2,choices=start_month_choices,default='1') end_month=models.CharField(max_length=2,choices=end_month_choices,default='1') views.py if request.method=='POST': contents=Tour.objects.all() category1= request.POST['category'] category2=request.POST['place'] start_date=request.POST['startdate'] end_date=request.POST['enddate'] datem_start = datetime.datetime.strptime(start_date, "%Y-%m-%d") start_month1=datem_start.month datem_end = datetime.datetime.strptime(end_date, "%Y-%m-%d") end_month1=datem_end.month tour_data … -
How to mail a pdf file stored in the database in the media folder to a user -Django
I have a model that stores some pdf files. I want to mail a pdf file as an attachment when a user requests to do so. I tried a way to do it like this @api_view(['POST']) def send_pdf_to_user(request): id = request.data.get('id') try: query = Civil.objects.get(id=id) file = query.pdf_file email = EmailMessage( 'Subject here', 'Here is the message.', 'from@me.com', ['user@gmail.com']) email.attach_file(file) email.send() return Response(status=200) except Exception as e: print(e) return Response({str(e)}, status=400) but received this error expected str, bytes or os.PathLike object, not FieldFile The file when printed gives this which is the path where the file is being stored civil/random.pdf Please suggest to me the way to mail pdfs which are pre stored in the database. -
How would I pass request.user into my form?
I'm trying to create a posts form that lets the user create posts on my site. I've been stuck on how to pass request.user into the fields "author" and "participants". Could anybody help? Here is my view: def home(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): form.save() return redirect('') My model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) participants = models.ManyToManyField(User, related_name="participants", blank=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-created"] def __str__(self): return self.body And my form: from django.forms import ModelForm from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = '__all__' -
How can I override the Django DurationField model to input minutes instead of seconds?
I'm trying to create a custom Duration Model, I'm just not sure about how this is done, the documentation is slightly confusing when it is explaining how to create custom model fields, and I am new to Django. https://docs.djangoproject.com/en/4.0/howto/custom-model-fields/ -
How Can I get Sum Total of Django Model Column through a Queryset
I am working on an Event App where I want to get the Total Amount of Pin Tickets that has been activated and I don't know how to do it. Below is what I have tried and I am getting this error: 'QuerySet' object has no attribute 'ticket' Here are my Models class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) price = models.PositiveIntegerField() category = models.CharField(max_length=100, choices=PASS, default=None, blank=False, null=False) added_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.event} " #Prepare the url path for the Model def get_absolute_url(self): return reverse("ticket-detail", args=[str(self.id)]) def generate_pin(): return ''.join(str(randint(0, 9)) for _ in range(6)) class Pin(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) value = models.CharField(max_length=6, default=generate_pin, blank=True) added = models.DateTimeField(auto_now_add=True, blank=False) reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) status = models.CharField(max_length=30, default='Not Activated') #Save Reference Number def save(self, *args, **kwargs): self.reference == str(uuid.uuid4()) super().save(*args, **kwargs) def __unicode__(self): return self.ticket class Meta: unique_together = ["ticket", "value"] def __str__(self): return f"{self.ticket}" def get_absolute_url(self): return reverse("pin-detail", args=[str(self.id)]) Here is my Views.py from django.db.models import Count, Sum def profile(request): amount_sold_pins = Pin.objects.filter(status='Activated') total_sold_tickets = amount_sold_pins.ticket.price total = total_sold_tickets.aggregate(total = Sum('price')).get('total') or 0 context = { 'guest':reservations, 'total':total, } return render(request, 'user/profile.html', context) Someone should please help with the best way of … -
How to make a python script to work with Django
so I have a python script I'd like to integrate to work with python. No matter what I do I don't seem to get it right. Below are what I've managed to do successfully which is getting Django to accept picture upload and display them to the user. https://replit.com/@Eddyah5/ImageConverterwithHTML#main.py I'm now trying to get my python script in the link above to work in Django to let users upload pictures out of the list of supported formats, convert the picture to .ico of different sizes, and zip them for download by users. Please pardon me I'm very new to python/Django. What to do with the views.py, models.py as pertaining my code is in the link below? https://replit.com/@Eddyah5/ImageConverterwithHTML#main.py I'm very new to python and Django, so any help I will deeply appreciate.