Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
return single instance of message django
i'm trying to create a p2p messaging system in my chat app (not using channels) so in my view.py i list out all messages, but i don't want it to list out multiple messages from a single user, just the most recent, sad to say it does the exact opposite, if brings out all messages between 2 people instead of only the most recent, i tried creating a different models so i can filter by that and add the distinct function, but still didn't work, i really wanna get this done by christmas, so i appreciate any help views.py def pmpage(request): user = recceiver.objects.get(id=request.user.id) all_message = pm.objects.filter(recepient=user).distinct() unread = pm.objects.filter(recepient=user, unread=True).order_by('sender').distinct() sent = pm.objects.filter(sender=request.user) context = { 'all_message' : all_message, 'unread' : unread, 'sent' : sent, } return render(request, 'message.html', context) models.py class recceiver(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.name) class pm(models.Model): sender = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE) recepient = models.ForeignKey(recceiver, related_name='recceiver', on_delete=models.CASCADE, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) body = models.TextField() unread = models.BooleanField(default=False) def __str__(self): return f'{self.body}' thanks again -
Where are built-in methods of django model manager defined in source code?
By default, django model's default manager objects has below built-in methods: all(), filter(), exclude(), get(), create(), order_by() But I did not find where are those methods defined in Django source code ? -
Django - Date field support time zone?
I'm working with Django Date field and was wondering if it supports time zone. Doesn't seem like it does because when I attach a time zone to the date it gives an error. Is there a reason for this? Wouldn't something like 11:30pm PST at 12/20/2021 give like 12/21/2021 in UTC? -
How to call an API POST method only inside another API method in Django Rest Framework
I was going through DRF, I want to call one API function which have GET and POST method inside another API function which also have get and post method. whether both get and post method will be called or Is it any way that I can achieve it. I was googling I didn't get any proper approach If some one can demonstrate it would be helpful. what if I want to call POST method in another function? -
Exporting multi table from same databases using django in Swagger
I have two table dataset 1. first_name 2. last_name first_name table looks like f_name | state --------------- raj | UP ravi | MP rahul | JK last_name table looks like l_name | state --------------- sharma | UP singh | MP gupta | JK and django model.py looks like class first_name(models.Model): f_name = models.CharField(max_length=50) state = models.CharField(max_length=50) class last_name(models.Model): l_name = models.CharField(max_length=50) state = models.ForeignKey(first_name, on_delete=models.CASCADE, related_name="last_name", null=True, blank=True, db_column='state') so in django I made importexport.py file and wirte code for import and export of first_name and last_name data sepearatly using this code from import_export import resources from name_management.models import first_name, last_name class first_nameResource(resources.ModelResource): class Meta: model = first_name skip_unchanged = True report_skipped = False use_bulk = True force_init_instance = True skip_diff = True def import_row(self, row, instance_loader, **kwargs): row_result = self.Meta.model.objects.update_or_create(f_name=row[1], defaults={'state': row[2]}) class last_nameResource(resources.ModelResource): class Meta: model = last_name skip_unchanged = True report_skipped = False use_bulk = True force_init_instance = True skip_diff = True def import_row(self, row, instance_loader, **kwargs): row_result = self.Meta.model.objects.update_or_create(l_name=row[1], defaults={'state': row[2]}) and In django views.py file I have created get and post method for importing / Exporting data table class ImportExportViewSet(views.APIView): permission_classes = [permissions.AllowAny] http_method_names = ['get', 'post'] parser_classes = (FormParser, MultiPartParser) def get(self, request, *args, … -
Error while sending PDF through Django link
Fairly New to Django Here. I tried sending a CSV successfully using this code but I'm getting the following error sending a pdf file I generated using PDFpages from matplotlib UnicodeDecodeError: 'utf-8' codec can't decode byte 0xac in position 10: invalid start byte Here's the code def download_file(request): # fill these variables with real values fl_path = 'file.pdf' filename = 'report.pdf' fl = open(fl_path, 'r', encoding='utf-8') mime_type, _ = mimetypes.guess_type(fl_path) print(mime_type) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response Is there a way to know which is the correct encoding I need to send my file through? -
How to display N number of Backward relationship in Django templates?
{% for category in categories %} {% for product in categories.product_set.all %} <h1> {{ product.name }} </h1> {% endfor %} {% endfor %} I want to show 10 products instead of all in template -
How do I upload a txt flatpage into a django based website
What I want to do is, I have a file called abc.txt. I want to upload this into to my website so that it shows on the browser as mysite.com/.well-known/pki-validation/abc.txt. The file (page) contains some text. I want to do this from terminal by creating a flatpage. I have created views.py and url. Daniel -
Calling a function name inside a function in Django Rest Framework
I have tried to call the two method inside the function where I couldn't able to call those method. I have tried few approaches but not succeeded. Here, What I have tried "UserStartShift", "UserStopShift" are the API functions which have GET and POST method in it. These API are working fine individually, I wanted to return a different response using the conditional statement. views.py: @api_view(['GET']) def UserShiftDetailsView(request, userid): try: users = tblUserShiftDetails.objects.filter(UserId=userid) except tblUserShiftDetails.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': if UserStartShift == True: cursor = connection.cursor() cursor.execute('EXEC [dbo].[USP_GetCurrentShiftDetails] @UserId=%s',(userid,)) result_set = cursor.fetchall() for row in result_set: row = row[0] return Response({"IsStarted":True,"EstimatedShifEnd":(row + datetime.timedelta(hours=9)).strftime('%d-%m-%Y %H:%M %p'),"ReasonforAccess": "null"}) elif UserStopShift == True : cursor = connection.cursor() cursor.execute('EXEC [dbo].[USP_GetCurrentShiftDetails] @UserId=%s',(userid,)) result_set = cursor.fetchall() for row in result_set: row = row[0] return Response({"IsStarted":False,"EstimatedShifEnd":"null","ReasonforAccess": "null"}) -
post type is not working in knockout js with ajax call
knockout.js <script> $(document).on('click', '#submit', function(e) { var viewModel = { title:ko.observable(),description:ko.observable(), mySubmit : function(formElement) { var formData = { 'title' : viewModel.title() , 'description' : viewModel.description() }; $.ajax({ type: "POST", url: '{% url "productscreate" %}', data: formData, contentType: "application/json; charset=utf-8", success: function (){ window.location = '{% url "productslist" %}'; }, error: function(xhr, errmsg, err) { console.log(xhr.status + ":" + xhr.responseText) } }); } }; ko.applyBindings(viewModel); </script> In this ajax knockout js code post type is not working. When i click submit button form value is displaying in url but i have done post type in ajax Please help me to solve this Thanks in advance -
How to put and access a file with FFmpeg in Google Cloude Storages?
Hi I am a novice developer and deployed my first django project on Heroku. I want to compress it into ffmpeg and save it to Google Cloud Storage when the user uploads a video file from uploadForm in the Django project.And by extracting the duration from the saved video using ffprobe and storing it in the duration field of object. Save() of My forms.py code is as follows: def save(self, *args, **kwargs): def clean_video(self): raw_video = self.cleaned_data.get("video") timestamp = int(time()) raw_video_path = raw_video.temporary_file_path() print(raw_video_path) video_name = f"{raw_video}".split(".")[0] subprocess.run(f"ffmpeg -i {raw_video_path} -vcodec libx265 -crf 28 -acodec mp3 -y uploads/videoart_files/{video_name}_{timestamp}.mp4", shell=True) return f"videoart_files/{video_name}_{timestamp}.mp4" videoart = super().save(commit=False) videoart.video = clean_video(self) video_path = videoart.video.path get_duration = subprocess.check_output(['ffprobe', '-i', f'{video_path}', '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv=%s' % ("p=0")]) duration = int(float(get_duration.decode('utf-8').replace("\n", ""))) videoart.duration = duration return videoart After all the validation of the other fields, I put the code to process the video inside the save method to compress the video at the end. Anyway, this code is not a problem in the local server it works very well. However, the server gets a NotImplementedError ("This backend dogn't support absolute paths.") error. Naturally, ffmpeg can receive input videos from temporary_file_path(), but it doesn't find a … -
Select first image of image foreign key in django template
I want to select first image of an object property set. I created a Property Model with a Foreign Key to an PropertyImages model. How do I access the first image of the property object_set.all in the template. I don;t want to do it in the view function since this should be in the base.html file. the code: {% for property in properties %} <div style="background-image: url('{{property.propertyimages_set.all|first.url}}'); background-size: 100% 100%; " ; class="tm-row-featured" > <div class="featured-content"> <p><span>Name: </span>{{property.property_name}}</p> <hr> <p><span>Type: </span>{{property.property_type}}</p> <p><span>Price: </span>&#8358;{{property.price}}</p> <p><span>Location: </span>{{property.property_state}}</p> <p><a href="{% url 'property_details' property.property_slug %}">More info >>></a></p> </div> </div> {% endfor %} -
how to fecth data from one to many database in django?
class Company(TimeStampedModel): name = models.CharField(max_length=200) hr_name = models.CharField(max_length=200) hr_email = models.CharField(max_length=200) user = models.ForeignKey( settings.AUTH_USER_MODEL, models.DO_NOTHING) hr_verified = models.BooleanField(default=False, blank=True) primary_phone = models.CharField(null=True, max_length=200) followed_by = models.CharField(max_length=200,default="Not assigned") comments = models.TextField(default="") def __str__(self): return self.name class FutsalUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField( ('staff status'), default=True, help_text=('Designates whether the user can log into this admin site.'), ) objects = FutsalUserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email these are models , i want to fecth the details in to one table -
How to get the first/second/third... Mondays of each month in a datetime list
Say I have a date list of Mondays like this: [datetime.date(2021, 12, 6), datetime.date(2021, 12, 13), datetime.date(2021, 12, 20), datetime.date(2021, 12, 27), datetime.date(2022, 1, 3), dateti me.date(2022, 1, 10), datetime.date(2022, 1, 17), datetime.date(2022, 1, 24), datetime.date(2022, 1, 31), datetime.date(2022, 2, 7), datetime.date(20 22, 2, 14), datetime.date(2022, 2, 21), datetime.date(2022, 2, 28), datetime.date(2022, 3, 7), datetime.date(2022, 3, 14), datetime.date(2022, 3, 21) , datetime.date(2022, 3, 28), datetime.date(2022, 4, 4), datetime.date(2022, 4, 11), datetime.date(2022, 4, 18), datetime.date(2022, 4, 25), datetime .date(2022, 5, 2), datetime.date(2022, 5, 9), datetime.date(2022, 5, 16), datetime.date(2022, 5, 23), datetime.date(2022, 5, 30)] how can I get the first Mondays of each month? -
Django send Gmail using.core.mail import send_mail: ConnectionRefusedError: No connection could be made because the target machine actively refused it
In gmail account security I turned ON the following: Access to less secure apps Signing in with 2-Step Verification In settings.py EMAIL_BACKEND = ‘django.core.mail.backends.smtp.EmailBackend’ EMAIL_HOST = ‘smtp.gmail.com’ EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = ‘myemailaddress@gmail.com’ EMAIL_HOST_PASSWORD = ‘mypassword’ Cannot figure out why getting the error: ConnectionRefusedError at /email_link_spi/951437/ [WinError 10061] No connection could be made because the target machine actively refused it. -
Return render is not rendering the html page
(views.py) I have this simple view: def edit_project(request): context = {} projects = Project.objects.all().values() project_id = request.POST['project_id'] if request.method == 'POST': print("Project ID: ", project_id) context['projects'] = projects return render(request, 'edit_project.html', context) return render(request, 'edit_project.html', context) The view edit_project is executed from another page (project_page.html) and its view , project_page : def project_page(request, reference): context = {} User = get_user_model() users = User.objects.all() context['users'] = users context['project_values'] = Project.objects.get(project_code=reference) project_id = Project.objects.filter(project_code = reference).values('id') if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_hist = form.save(commit=False) file_hist.user = request.user file_hist.save() file_hist_results = FileHistory.objects.all().filter(user=request.user) context['file_hist_results'] = file_hist_results return render(request, 'project_page.html', context) print (form.errors) else: form = UploadFileForm() file_hist_results = FileHistory.objects.all().filter(user=request.user) context['file_hist_results'] = file_hist_results context['form'] = form return render(request, 'project_page.html', context) edit_project view is called from project_page.html in the following way: <script type="text/javascript"> $(document).ready(function() { const projectEdit = document.getElementById("projectEditBtn"); projectEdit.onclick = function() { var pid = "{{ project_values.id }}"; var project_id = document.createElement("input"); var form = document.getElementById("edit-project-form"); project_id.setAttribute('type', 'text'); project_id.setAttribute('value', pid); project_id.setAttribute('name', 'project_id'); form.appendChild(project_id); form.submit(); }; }); </script> urls.py: path('edit_project/', views.edit_project, name='edit_project'), Apparently the view works correctly, no browser console errors, I can even print in the terminal the content of the request.POST (which means that the form is fine): but … -
How to render data selected choice on templates with bootstrap in DJANGO
Im Create Gender with field ('jenis_kelamin') in my models Male('Pria') and Female('Wanita'). But, when i post the data, data is not render. display on my template. DISPLAY ON MY TEMPLATE display on my Admin Page. DISPLAY ON MY ADMIN PAGE How to Fix That ? This is My : models.py class UserProfil(models.Model): JENIS_KELAMIN_CHOICE = ( ('Pria', 'Pria'), ('Wanita', 'Wanita' ), ) #Profil user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) gelar_depan = models.CharField(max_length=11, blank=True, default="") gelar_belakang = models.CharField(max_length=20, blank=True, default="") nik = models.CharField(max_length=11, blank=True, unique=True, default="") nidn = models.CharField(max_length=11, blank=True, unique=True, default="") email_alternatif = models.EmailField(_('email address'), blank=True, default="") jenis_kelamin = models.CharField(max_length=6, blank=True, default="", choices =JENIS_KELAMIN_CHOICE) tempat_lahir = models.CharField(max_length=30, blank=True, unique=True, default="") tanggal_lahir = models.DateField(null=True, blank=True) nomor_handphone = models.CharField(max_length=13, blank=True) alamat = models.CharField(max_length=255, blank=True, default="") forms.py class UserProfilUpdateForm(ModelForm): class Meta: model = UserProfil exclude = ['user'] widgets = { 'gelar_depan' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'gelarDepan', 'placeholder' : 'Gelar Depan'}), 'gelar_belakang' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'gelarBelakang', 'placeholder' : 'Gelar Belakang'}), 'nidn' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'nidn', 'placeholder' : 'Nomor Induk Dosen Nasional'}), 'nik' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'nik', 'placeholder' : 'Nomor Induk Karyawan'}), 'tempat_lahir' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'gelarBelakang', 'placeholder' : … -
how to serve static files from EKS cluster for Django?
I am new to Kubernetes. By reading some blogs and documentation I have successfully created the EKS cluster. I am using ALB(layer 7 load balancing) for my Django app. For controlling the routes/paths I am using the ALB ingress controller. But I am unable to serve my static contents for Django admin. I know that I need a webserver(Nginx) to serve my static files. I'm not sure how to configure to serve static files. note: (I don't want to use whitenoise) -
Django access manytomany field from related_name in a view
I have what i think is a simple question but I am struggling to find out how it works. I get how related name works for foreign keys but with many to many fields it seems to break my brain. I have two 3 models at play here. A User, TeamMember and Team Model as seen below. User model is the built in django model. #TeamMember Model class TeamMember(models.Model): member = models.ForeignKey(User, on_delete=models.SET(get_default_team_member), verbose_name='Member Name', related_name="team_members") ... #Team Model class Team(models.Model): name = models.CharField(max_length=50) manager = models.ForeignKey(TeamMember, on_delete=models.SET_NULL, related_name="managers", null=True, blank=True) team_lead = models.ForeignKey(TeamMember, on_delete=models.SET_NULL, related_name="tls", null=True, blank=True) tps = models.ForeignKey(TeamMember, on_delete=models.SET_NULL, related_name="tps", null=True, blank=True) members = models.ManyToManyField(TeamMember, blank=True, related_name="members") ... Now in a view i want to access a specific users team. I thought i could do this by doing something like this: member = TeamMember.objects.get(pk=1) member_team = member.members.name However if I print member_name than it prints nothing. If I try to access any of the other fields on that model like member.members.team_lead.first_name it fails to find the team_lead field. I understand that this has a .all() attribute but i thought it was tied to the team object through the members field. So if that member matches the team … -
Django how access result from queryset in template from index
I have a queryset result in a template: {% for image in product.productimages_set.all %} <img src="{{ image.image_file.url }}"/> {% endfor %} How could I access a index of that object in a template, ie: <img src="{{ product.productimages_set.all.0 }}"/> -
Updating Django model with OneToOne field yields "Duplicate entry for id"
I have a PUT request that should update my Django model with a OneToOne field linking to another model. After running this successfully once, if I try it again, on serialize.save() I get a (1062), Duplicate entry '1 for key 'linked_model_id'. In my models.py: class ModelToUpdate linked_model = (LinkedModel, null=False, on_delete=models.deletion.CASCADE) other_stuff In my views.py: class ModelToUpdateView(arg): def put(self, request): linked_model = request.linked_model model_to_update = (linked_model.model_to_update if hasattr(linked_model, 'model_to_update') else ModelToUpdate(linked_model=request.linked_model) ) serializer = ModelToUpdateSerializer(model_to_update, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In serializers.py: class ModelToUpdateSerializer(): class Meta: model = ModelToUpdate fields = ['all', 'my', 'fields', 'in', 'the', 'model'] This is the same format as other models in the app with OneToOneFields that are updating successfully. -
In Django, if my request returns a username, can I also get the user's first and last name?
I'm building a Django app for a law firm to let them assign incoming cases to the firm's lawyers. The lawyers are the users, so I used a list of the lawyers to make a dropdown of their usernames, so it's easy to select an active lawyer for the assignment. In some of the templates I create, it's not hard to show the full name of the assigned lawyer. I use "client.assignee.get_full_name", and it shows "John Attorney". But that's a piece of data that seems to ride along with the Client model. I can also get first and last names in my menu dropdowns by querying the list of attorneys through a context processor: def attorney_menu(request): return { 'attorneys': User.objects.filter(groups__name='attorney-staff') } The code to produce that is: <ul class="dropdown"> {% if attorneys %} {% for attorney in attorneys %} <li><a href="/by_attorney?username={{ attorney.username }}">{{ attorney.first_name }} {{ attorney.last_name }}</a></li> {% endfor %} {% endif %} </ul> All the above is working fine. However, in the admin, in the templates created by the default Django admin, my dropdowns can only show the username ("johnattorney" instead of "John Attorney"). Also in the attorney pages (the pages that show the attorney's individual assigned clients), … -
Django object_list from ListView with two models
I have two models, and need access property from both. models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=255, default='product_title') product_description = models.CharField(max_length=255, default='product_description') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) product_view = models.IntegerField(default=0) def __str__(self): return self.product_title def get_absolute_url(self): return reverse('product_change', kwargs={'pk': self.pk}) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_type = models.CharField(max_length=33,default='image_type') image_file = models.ImageField( upload_to='images/', null=True, blank=True, default='magickhat-profile.jpg' ) ProductImages is a model to store multiple images. views.py class ProductListView(ListView): model = Product template_name = 'product_list.html' product_list.html ... {% for product in object_list %} <div class="product"> {% include 'label_perfil.html' %} {% include 'data_product.html' %} </div> {% endfor %} ... data_product.html {% block data-product %} <img src="{{ product.image_file }}"/> {% endblock %} All properties from Product model is available, but how ca access product.image_file data? That return empty... Django 3.2 -
Annotating on a distinct Django Queryset is no longer using the distinct queryset
I have a query and I am trying to annotate the count of each value for the field tail_tip. My original query filters on a related table so it is necessary to use distinct(). I'm not exactly sure how to describe but it appears when I annotate the distinct query the query is no longer distinct. Here are my queries I am playing with in my shell. // Without distinct() Ski.objects.filter(published=True, size__size__in=[178, 179, 180, 181, 182, 183, 184]).count() // 318 skis = Ski.objects.filter(published=True, size__size__in=[178, 179, 180, 181, 182, 183, 184]).distinct() skis.count() // 297 skis.values('tail_tip').order_by('tail_tip').annotate(count=Count('tail_tip')) // <QuerySet [{'tail_tip': 'flat', 'count': 99}, {'tail_tip': 'full_twin', 'count': 44}, {'tail_tip': 'partial_twin', 'count': 175}]> // total count = 318 Given that skis is already distinct() I don't know why when I annotate it the total count then equals the non-distinct query. -
Trying to import a webstie template throught Django and keep getting this error
Every time I try and run the template I get this error: Refused to apply style from '' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Is there a place I can go to disable strict MIME checking?