Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework : Generics custom method for "RetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView)" not working
In this generic APIView when I'm trying to log in through a nonadmin user it is giving "detail": "You do not have permission to perform this action." but working fine for admin user. I don't whether the problem is in code or permission.py I've shared my Views.py, permissions.py and models.py for the same. class BookingRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsUserOrIsAdmin] # queryset = Booking.objects.all() # serializer_class = BookingSerializer def get_queryset(self): if self.request.user.is_admin == False: user_data= self.request.user book = Booking.objects.filter(user= user_data) return book else: book = Booking.objects.all() return book serializer_class = BookingSerializer permissions.py from django.contrib.auth import get_user_model from rest_framework.permissions import BasePermission User = get_user_model() class IsUserOrIsAdmin(BasePermission): """Allow access to the respective User object and to admin users.""" def has_object_permission(self, request, view, obj): return (request.user and request.user.is_staff) or ( isinstance(obj, User) and request.user == obj ) views.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','contact_number','gender','address','state','city','country','pincode','dob'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible … -
Error- unsupported operand type(s) for -: 'str' and 'datetime.timedelta' In Django
Hi Everyone i have working on Django-framework, I am created on function where i give parameter start_date and end_date, i am trying get previous week start_date and end_date based on start_date but getting Error - unsupported operand type(s) for -: 'str' and 'datetime.timedelta', please help me out. from datetime import datetime, timedelta, date def report(request): start_date = request.GET.get('start_date') print(start_date) # 2022-06-06 end_date = request.GET.get('end_date') print(end_date) # 2022-06-12 last_week_start_date=start_date - timedelta(days=7) last_week_end_date=last_week_start_date + timedelta(days=6) d_report = connection.cursor() d_report.execute('''select * from table where start_date=%s and end_date=%s''',[start_date,end_date]) -
How to fetch row data value or id from datatable on checkbox and add in to the broadcast list select in django python template?
How to fetch row data value on checkbox select and add to the list on button click event? We are trying to get values on select on check box and try to add on list but we don't know how to integrate django variable to javascript? I am new to python and djnago so need guidence javascript code: function showDiv() { var form = document.getElementById("myform"); form.submit(); } function selectAll(){ var ele=document.getElementsByName('seluserid'); for(var i=0; i<ele.length; i++){ if(ele[i].type=='checkbox') ele[i].checked=true; } } function deSelectAll(){ var ele=document.getElementsByName('seluserid'); for(var i=0; i<ele.length; i++){ if(ele[i].type=='checkbox') ele[i].checked=false; $(".btnbrdcstlist").hide(); } } function getvalues() { var val = []; $(':checkbox:checked').each(function (i) { // alert("In each function"); val[i] = $(this).val(); console.log(val[i]); }); } function Showbrdcstbtnv() { if ($('.cstm').is(":checked")) $(".btnbrdcstlist").show(); else $(".btnbrdcstlist").hide(); } function showDiv() { var form = document.getElementById("myform"); form.submit(); } Html Code: <button class="btn btn-primary" type="button" id="selectall" onclick="selectAll(),Showbrdcstbtnv(this)">Select All</button> <button class="btn btn-primary" type="button" id="deselectall" onclick="deSelectAll()">Deselect All</button> <!-- Checkbox select Datatable start for opt-1 --> <div class="row justify-content-end btnbrdcstlist " id="btnbrdcstlist" style="display:none"> <a href="{% url 'adduser' bid=adduser.id %}" class="btn btn-primary" style="margin-bottom: 15px;">Add To Broadcastlist</a> </div> Datatable code : <table class="table nowrap checkbox-datatable" id="usertbl"> <thead> <tr> <th> <!-- <div class="dt-checkbox"> <input type="checkbox" name="select_all" value="1" id="example-select-all" class="cstm" onclick="Showbrdcstbtnv(this)" /> <span class="dt-checkbox-label"> </span> </div> … -
Django Rest Framework gives "I/O operation on closed file" this kind of error while uploading an image
When i try to create objects in a loop which contains data in image field, in first time the object is created and in the next iteration it gives "I/O operation on closed file" this kind of exception. for student in data: student_obj = StudentRegistration.objects.filter(id=student) student = student_obj.first().name if student: obj = StudentDetails.objects.create(student=student_obj.first(), age=request.data.get('age'), photo=request.FILES.get('photo'), created_on=created_on_time) -
Ternary codes of countries in django_countries
I need to list the ternary codes of countries in django_countries but I can not reach the list my import : from django_countries import countries ... def populate_countries(): for country in list(countries): Country.objects.get_or_create( country_name=country.name, country_code=country.code ) ... >>> AttributeError: 'CountryTuple' object has no attribute 'alpha3' How can I reach them? -
How can I split deployments of Django apps in the same project with shared models and database?
I have an architectural question: We have a Django project made of multiple apps. There is a core app that holds the main models used for the other sets of apps. Then, we have a couple apps for user facing APIs. Lastly, we have some internal apps and tools used by developers only that are accessible in Admin UI as extended features. Our deployment process is very monolithic. We use Kubernetes and we deploy the whole project as a whole. Meaning that if we only had changes in an internal app and we need that in production, we will build a new Docker image and deploy a new release with a new version tag incremented. I'm not a big fan of this because change in internal tools shouldn't create a new release of the user facing applications. I have been wondering if there is a way to split those deployments (maybe make them into a microservice architecture?). So we could deploy the user facing applications separate from the internal tools. I know I could build separate images, tags and everything for parts of the project but I'm not sure how they could communicate between each other if internal_app_1 depends on … -
django.db.utils.OperationalError: sub-select returns 8 columns - expected 1
I'm attempting to generate a QuerySet that collects all the tags that are posted in all of a given user's posted questions. On top of that, annotate over each Tag instance to find out how many times each tag was posted. The problem I'm encountering however is with the following error that is being raised: django.db.utils.OperationalError: sub-select returns 8 columns - expected 1 What is this error referring to and how can it be resolved in order to get the aforementioned desired QuerySet? class TestProfileInstanceTagData(TestCase): @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user("ItsMe") profile = Profile.objects.create(user=cls.user) tag1 = Tag.objects.create(name="TagA") tag2 = Tag.objects.create(name="TagB") tag3 = Tag.objects.create(name="TagZ") question1 = Question.objects.create( title="This is a title about question1", body="This is the post content about question1", profile=profile ) question1.tags.add(tag3) question2 = Question.objects.create( title="This is a title about question2", body="This is the post content about question2", profile=profile ) question2.tags.add(*[tag1, tag3]) question3 = Question.objects.create( title="This is a title about question3", body="This is the post content about question3", profile=profile ) question3.tags.add(tag2) cls.queryset = profile.get_tag_post_data() def test_user_posted_tag_queryset(self): self.assertEqual(self.queryset.count(), 3) class Profile(Model): user = OneToOneField(settings.AUTH_USER_MODEL, on_delete=CASCADE) def get_tag_post_data(self): questions_with_tag = self.questions.filter(tags__name=OuterRef("name")) return Tag.objects.filter( question__profile=self ).distinct().annotate(count=Count(Subquery(questions_with_tag))) class Tag(Model): name = CharField(unique=True, max_length=25) class Post(Model): body = TextField() date = DateField(default=date.today) comment = ForeignKey('Comment', … -
gpu usage from Cilent Server Runtime Process when running Django 'python manage.py' on localhost:8000
Does anyone have this same issue? My task manager shows Client Server Runtime Process at around 6% after I run the cmd 'python manage.py runserver' on localhost:8000. I've turned on my Hardware-accelerated GPU scheduling on my windows game graphics settings per this video https://www.youtube.com/watch?v=EGBCpB57yWU This worked after I restarted my computer, Client Server Runtime Process showed 0% gpu.. but as soon as I run my dev server it went back to around 6%. I scanned my pc with Norton and Malwarebytes.. nothing.. Updated everything to no avail. CPU: i7 9700k GPU: 2070 super 30gb ram 1tb Samsung M.2 for boot -
how to set DTL(Django Tamplate language) for loop and value through javascript
I want to set django for loop to set value through javascript like this. is this correct way? or Is there any other way? var table = $('.checkbox-datatable').DataTable({ 'scrollCollapse': true, 'autoWidth': false, 'responsive': true, "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]], "language": { "info": "_START_-_END of TOTAL_ entries", searchPlaceholder: "Search", paginate: { next: '<i class="ion-chevron-right"></i>', previous: '<i class="ion-chevron-left"></i>' } }, 'columnDefs': [{ 'targets': 0, 'searchable': false, 'orderable': false, 'className': 'dt-body-center', 'render': function (data, type, full, meta){ return '<div class="dt-checkbox"><input type="checkbox" name= "id[]" id="chkuser" value="' + {% for dd in departmentData %}{{dd.id}}{% endfor %} + '" /><span class="dt-checkbox-label"></span></div>'; } }], 'order': [[1, 'asc']] }); -
What the best online storage option for my Django project? [closed]
I’m fairly new to Django and would like to know about the best available online storage options. I’ve done some research and I saw something about Amazon Web Services (AWS). Are there any other popular options that’s free where I don’t have to use my card to pay for these services? Just don’t want to pay since I’m only feeling out the options for now. Thanks for your suggestions in advance! -
Reverse for 'path' not found. 'function' is not a valid view function or pattern name?
I want to pass the argument to the function through the url. But I am getting error as Reverse for 'combodetails' not found. 'combodetails' is not a valid view function or pattern name. urls.py : path('combodetails/<int:id>/', combodetails, name="combodetails"), views.py : def combodetails(request, id): print(id) return render(request, "dashboard/combodetails.html", context={}) .html : <a href="{% url 'dashboard:combodetails' model.id %}" class="icuwfbegb"> I have used the same method in other functions and they are working fine. But here I don't know what's happening? -
Django Models making unique ,unique_together
I am a beginner and building Real-Time Chat with Django Web Sockets for my portfolio ,so I have model Thread that contains first_person and second_person , so it is like one to one room . from django.db import models from django.contrib.auth.models import User # Create your models here. from django.db.models import Q class ThreadManager(models.Manager): def by_user(self, **kwargs): user = kwargs.get('user') lookup = Q(first_person=user) | Q(second_person=user) qs = self.get_queryset().filter(lookup).distinct() return qs class Thread(models.Model): first_person = models.ForeignKey(User,on_delete = models.CASCADE,related_name='first_person') second_person = models.ForeignKey(User,on_delete = models.CASCADE,related_name='second_person') objects = ThreadManager() updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('first_person', 'second_person') My problem is that , i want to make this Thread model unique . I used unique_together, as you can see in Thread model ,but it only works for one way .For example , if i enter first_person : Alex and second_person : Sam ,it saves . But in vice versa , it also saves,if i change the places of people ,like : first_person :Sam and second_person : Alex . I also tried this code in my admin.py: class ThreadForm(forms.ModelForm): def clean(self): super(ThreadForm, self).clean() first_person = self.cleaned_data.get('first_person') second_person = self.cleaned_data.get('second_person') lookup1 = Q(first_person=first_person) & Q(second_person=second_person) lookup2 = Q(first_person=second_person) & Q(second_person=first_person) lookup = Q(lookup1 … -
Probably a very basic question: can I build and maintain the same website (in Django) from both Windows and macOS?
Disclaimer: First, I apologise if I'm incorrectly applying technical terms here or, worse, completely misunderstanding things. I'll edit if corrected. Context: Lately I've been building and deploying some basic website ideas to Heroku using the Django framework. I've been doing this on Windows, using venv as my virtual environment "wrapper". I've been building these exclusively from the command line interface. I also have a MacBook that I'd like to use to access and manage those websites, and in future, larger projects. I would prefer not to install Windows on this MacBook. To be clear, I know that it's possible to build and deploy a website using Django and Heroku on macOS. I know there are, at the very least, some syntactical differences in how I would approach this from the CLI versus Terminal. Desired outcome: I would like to set up a website in the fashion indicated above on Windows or macOS, and then access and manipulate it from the other OS. Questions: Is this possible? (Or if I set it up on Windows must I only use Windows to manage it?) If I set up a website in this fashion using Django, Heroku, and venv on Windows, how (if … -
Get value list from ManytoMany Queryset
I have two models Bookings and Presenter, which are setup as a Many to Many Field. I then have a function called 'export excel' (found on online tutorial) , which exports all of the data from the Booking model to an Excel spreadsheet. Each booking may contain more than one presenter. Currently the export works but displays a new record for bookings that have more than one presenter assigned. Is it possible to get the presenter name be displayed as a list? rather than duplicating the booking on a new row. So for example if booking 1 contains two presenters the names will display as ['mark', 'jake'] Queryset used in export excel function rows= Bookings.objects.all().exclude(status='Cancelled').values_list( 'id', 'program_type', 'delivery_method', 'booking_date', 'booking_time', 'duration', 'school_name', 'year_level', 'street', 'suburb', 'post_code', 'contact_name', 'email', 'phone_number', 'comments', 'students_attending', 'status', 'presenter__name') Models class Presenter(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=10) role = models.CharField(max_length=50) def __str__(self): return self.name class Bookings(models.Model): statuses = [ ('TBC', 'TBC'), ('Confirmed', 'Confirmed'), ('Completed', 'Completed'), ('Cancelled', 'Cancelled'), ] id = models.BigAutoField(primary_key=True) program_type = models.CharField(max_length=40) delivery_method = models.CharField(max_length=40) booking_date = models.DateField() booking_time = models.CharField(max_length=10) duration = models.CharField(max_length=10) school_name = models.CharField(max_length=120) year_level = models.CharField(max_length=10) street = models.CharField(max_length=120) suburb = models.CharField(max_length=120) post_code … -
How do I display objects by day in Django template?
Right now, I have a few logs in my database that I want to display them by date in the Django template. How do I do it? This is how my current system looks like.. How I want them to look like.. JUNE 20, 2022 ------------- Nice songs! I'm listening to Massive Attack right now - 03:06 AM Just completed a sketch of the LOG IT! - 21:48 PM I'm watching a movie right now. It's called Black Swan - 21:30 PM Just had a pizza from Pagliacci! - 21:25 PM models.py class Logs(models.Model): log = models.CharField(max_length=100) created = models.DateTimeField(auto_now=False, auto_now_add=True) -
Context attributes not available in Django template
I'm trying to display a specific attribute in a template in Django. I believe I've passed the correct queryset in the context, but for some reason I'm only able to access the id attribute, and not the title attribute that I need. Views.py: @login_required def watchlist_view(request): listings = models.WatchedListing.objects.filter(owner = request.user) return render(request, "auctions/watchlist.html", {"listings": listings}) @login_required def add_to_watchlist(request, listing_id): listing = models.Listing.objects.get(pk=listing_id) user = request.user currently_watched = models.WatchedListing.objects.filter(owner = request.user) if listing in currently_watched.all(): messages.error(request, "This item is already on your watchlist.") return redirect(reverse('listing', args=[listing.pk])) else: watchlist = WatchedListing() watchlist.owner = user watchlist.watched_listing = listing watchlist.save() messages.success(request, "Added to your watchlist!") return redirect(reverse('listing', args=[listing.pk])) Models.py: class Listing(models.Model): title = models.CharField(max_length=64) description = models.TextField() start_bid = models.ForeignKey(Bid, on_delete=models.CASCADE, related_name="start_bid") image_url = models.TextField(null=True) category = models.CharField(max_length=64, null=True) current_bid = models.ForeignKey(Bid, on_delete=models.CASCADE, related_name="current_bid") is_active = models.BooleanField() owner = models.ForeignKey(User, on_delete=models.CASCADE) num_bids = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) class WatchedListing(models.Model): watched_listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='watched_listings', blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name ='watchlist_owner') watchlist.html: {% extends "auctions/layout.html" %} {% block title %} Watchlist {% endblock %} {% block body %} {% if messages %} {% for message in messages %} <strong style="color: red">{{ message }}</strong> {% endfor %} {% endif %} {% if listings … -
How can I make carousel Flex Message in Line Bot with Django?
I know how to show carousel message with using carousel template, however ,it can't show in Line when using computer. So I want to try not to use carousel template, I have seen these code for carousel Flex Message in JSON ,how can I switch these code to Django format? { "type": "carousel", "contents": [ { "type": "bubble", "body": { "type": "box", "layout": "vertical", "contents": [ { "type": "text", "text": "First bubble" } ] } }, { "type": "bubble", "body": { "type": "box", "layout": "vertical", "contents": [ { "type": "text", "text": "Second bubble" } ] } } ] } -
Django, AWS Elastic Beanstalk
Hope everyone is doing well. I'm trying to deploy a Django APP to elastic beanstalk however it is failing. The error is Following services are not running: web I'm not sure how to resolve it, I changed settings to be allowed_hosts = ['*'] but this still came up with the error. I'm concerned it may be the database connection? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': '***.***.ap-southeast-2.rds.amazonaws.com', 'PORT': '5432', } } Any help will be much appreciated I've googled and googled and tried and tried but no solutions have worked for me (works fine with manage.py runserver). The logs have not been much help to me as I don't understand them that well. When I attempt to connect I get this in the nginx logs. 4335#4335: *88 connect() failed (111: Connection refused) while connecting to upstream The daemon.log have these warnings: WARN -- : log file "/var/log/nginx/healthd/application.log.2022-06-20-01" does not exist The engine.log has these warnings: [WARN] Warning: process healthd is already registered... Deregistering the process ... [WARN] stopProcess Warning: process xray is not registered [WARN] deregisterProcess Warning: process httpd is not registered, skipping... (Note: This is my first time using AWS EB) -
How to create a custom migration to change the inbuilt django User model
I am having this problem in creating a custom User model in django and i actually posted this question before and I did get an answer from "@Sorin Burghiu" and it was very helpful since I did not even know the issue before but now I do know the issue but I don't know how to write my custom migration to do so let me post the answer here "Changing the user model mid-project is a difficult situation if you are trying to override the existing user model with a NewUser. Reference You will need to write a custom migration to do it to transfer all data from the current User table to the NewUser table, then drop the User table safely. If that's not the case and you just started the project, feel free to drop your current database and make migrations again after changing the default user model in settings.py (you are doing that already). Also make sure all imports in other files are undated to use your NewUser model instead of the django default User." This is the answer but I don't know how to write a migration for this and this is where i need some … -
"This field is required" error for FormSet when requesting payload, but works fine with Form
Need some help with this. If I pass a formset to a html template and request its payload with a POST request, I get this error Field Error: primary <ul class="errorlist"><li>This field is required.</li></ul> Field Error: symbol <ul class="errorlist"><li>This field is required.</li></ul> Field Error: secondary <ul class="errorlist"><li>This field is required.</li></ul> For the formset, the forms are dynamically added or deleted onto the page, but there will always be a single form on the page when the page is loaded. And for the other dynamically added forms, they get the same error as well. But when I pass a single form to the html template, I get the POST payload just fine. views.py def advanced(request): form = formset_factory(Search) if request.method == 'POST': formset = Search(request.POST) for field in formset: print("Field Error:", field.name, field.errors) return render(request,"advancedsearch.html", {"formset":form}) forms.py indicator = [ ('', ''), ('high', 'Estimated high'), ('low', 'Estimated low'), ('median', 'Estimated median'), ('realprice', 'Real Price'), ] symbol= [ ('', ''), ('>', 'higher than'), ('<', 'less than'), ('=', 'equal to'), ] class Search(forms.Form): primary = forms.CharField(label='a', widget=forms.Select(choices=indicator)) symbol = forms.CharField(label='b', widget=forms.Select(choices=symbol)) secondary = forms.CharField(label='c', widget=forms.Select(choices=indicator)) advancedsearch.html <form method="POST" action="">{% csrf_token %} {% for x in formset %} <div class = "d-flex flex-row justify-content-center … -
Add instead of replace Django
Why does this view replace what is in the addedauction instead of adding another listing? I would like to create a Watchlist in which the user can add an auction to its Watchlist after clicking on the link, but when i checked how it works it after adding one auction the next one simply replaces the first one. How do I put multiple auctions on a user's Watchlist? views.py def addtowatchlist(request, auctionurl): try: currentauction = get_object_or_404(Auctionmodel, id=auctionurl) print(currentauction) user_list, created = Watchlist.objects.get_or_create(owner=request.user) user_list.addedauction.add(currentauction) return HttpResponseRedirect(reverse("watchlist")) except TypeError: return HttpResponseRedirect(reverse("index")) models.py class Watchlist(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, related_name="ownerofwatchlist") addedauction = models.ManyToManyField(Auctionmodel, blank=True, related_name="auctionadd") -
Next Vercel frontend, how to connect to Elastic Beanstalk Django backend?
My Next frontend is already hosted on Vercel. How do I shoot my apis to my backend? I already have a django app running on elastic beanstalk but its health is in red condition and also its debug mode is set to True. I tried shooting postman APIs locally, it works with http://127.0.0.1:8000. but it doesn't with http://my-eb-site:8000 . How do I configure my elastic beanstalk django backend for production? Also how would i face CORS issue later on? -
If Operational error happens in django query in read database router, rerun the query on write database
When a read query from read_db() fails due to following error ERROR: cancelling statement due to conflict with recovery Detail: User query might have needed to see row versions that must be removed how to catch the error and rerun the same query on a write db. -
My code in terminal in vs code is disabled how to enable?
How to enable running script in visual studio in windows 11? When I'm running visual studio code terminal is said that my running script is disabled how can I fix it? -
How to redirect to url instead of error message? "Direct assignment to the forward side of a many-to-many set is prohibited."
I wish if the object exists in the database the user would just be redirected to "watchlist" instead I get the error "Direct assignment to the forward side of a many-to-many set is prohibited. Use addedauction.set () instead.". def addtowatchlist(request, auctionurl): Watchlist.objects.get_or_create(owner=request.user, addedauction=auctionurl) if Watchlist.objects.get_or_create(owner=request.user, addedauction=auctionurl) == False: return redirect("watchlist") return redirect("watchlist")