Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exclude Django admin fieldsets
Whats the best way of excluding fieldsets, I have been reading different posts like the one's below : Question. but I couldn't get it working with them. I want to negelect the following fieldsets when it's not superuser : Cooperation Partner Settings. email_user (This is an Inline not a field set) Below is the admin.py code @admin.register(CooperationPartner, site=admin_site) class CooperationPartnerAdmin(model.Admin): inline_type = 'stacked' inline_reverse = [( 'email_user', {'fields': [ 'salutation', 'title', 'first_name', 'last_name', 'email', ]}, )] reverse_delete_user = True form = CooperationPartnerAdminForm fieldsets_add = ( (_('Personal Data'), { 'fields': ( 'birthday', 'private_address_street', 'private_address_house_n', 'private_address_extra', 'private_address_postcode', 'private_address_city', ), }), (_('Cooperation Partner Settings'), { 'fields': ( 'pool', 'custom_policy_type', 'custom_database_structure', 'custom_attachments', ) }), (_('Company Data'), { 'fields': ( 'company', 'legal_form', 'business_address_street', 'business_address_house_n', 'business_address_extra', 'business_address_postcode', 'business_address_city', 'international_prefix', 'phone_number', 'career_position', 'loan_intermediary_permission', 'agreed_provision', 'bank_name', 'iban', 'bic', 'account_holder', 'sepa_direct_debit_mandate', 'status_decision_feedback', ), }), ) fieldsets_change = ( (None, { 'fields': ( 'cooperation_partner_id', 'account_state', ), }), ) + fieldsets_add def get_form(self, request, obj=None, change=False, **kwargs): """Overwrite get_form method.""" self.fieldsets = self.fieldsets_change if obj else self.fieldsets_add return super().get_form(request, obj, change, **kwargs) -
getting .count(), .exist() from cached queryset without hitting database
I am working on a Django app and I want to make several lookups in a queryset. My problem is subsequent database hits in finding .count() I tried using Django's cache framework but it doesn't seem to work. This is what I've done so far # app/models.py from django.core.cache.backends.base import DEFAULT_TIMEOUT from django.views.decorators.cache import cache_page from django.core.cache import cache class my_table(models.Model): class Meta: db_table = 'table_name' name = models.CharField(max_length=200, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True) ip_address = models.CharField(max_length=100, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def save(self, *args, **kwargs): cache.set(self.user , my_table.objects.filter(user=self.user)) super(my_table, self).save(*args, **kwargs) I am updating the cache every time the database is updated. I tried printing connection.queries in my views # views.py def myview(request): print(len(connection.queries)) # prints 0 records = my_table.objects.filter(user=request.user) print(records) print(len(connection.queries)) # prints 1 if record.count() > 0: # ... some code here print(len(connection.queries)) # prints 2 print() and .count() making extra db hits. Now I tried getting results from the cache # views.py def myview(request): print(len(connection.queries)) # prints 0 records = cache.get(request.user) print(records) print(len(connection.queries)) # prints 0 if record.count() > 0: # ... some code here print(len(connection.queries)) # prints 1 There was no extra query for print() but .count() still hitting database. how can I perform … -
How to set and manage a variable in django database without a parent Model
Let's assume I'm running a company, so I need to keep track how much money I have in my inventory, so I need a unique variable which stores an integer which contains the total money in my inventory... To be precise, I want a variable in my database without a parent model, like we generally do like this class ModelName(models.Model): How do I achieve that? Feel free to ask questions in the comments if I am not clear somehow. Thanks in advance :) -
Failed to fetch content for the given url - Django CKEditor on Heroku
I am using Django-CKEditor as a rich text editor for one of my applications. The problem is with the Media Embed plugin on Heroku. When I insert any URL in the Media Embed option it works fine in my local environment. But when I insert URL in my deployed application (on Heroku), It shows me a - "Failed to fetch content for the given url." error. Does anybody know why is this happening ? This are my CKEDITOR Configurations in settings.py file. CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'width': 'auto', 'toolbar_Custom': [ ["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"], ['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink", "Embed"], ['Undo', 'Redo'], ["CodeSnippet"], ["Maximize"] ], # Remove these dialog tabs (semicolon separated dialog:tab) 'removeDialogTabs': ';'.join([ 'image:advanced', 'image:Link', 'link:upload', 'table:advanced', #'tableProperties:advanced', ]), # Extra plugins to be used in the editor 'extraPlugins': ','.join([ 'mathjax', # Used to render mathematical formulae 'codesnippet', # Used to add code snippets 'image2', # Loads new and better image dialog 'embed', # Used for embedding media (YouTube/Slideshare etc) 'tableresize', # Used to allow resizing of columns in tables ]), } } -
Django REST detail view put form not filling correctly on POSTed content
I am having a strange error. I have a view called WrongMatch, which people using my app can suggest a change if a link is wrong. This is done over a POST request. When I make a WrongMatch inside the browsable API, I can enter its detail view and the PUT html form is filled correctly, but for the ones coming from the POST request, the first field in the PUT html form defaults to the first entry in the database. However, both entries looks identical to me. This picture shows two entries, the first one is POSTed from the app, and the second is made in the browsable API. This shows the detail view of the first entry, but as seen in the PUT html form, the beer defaults to the first in the database and not the one in the entry. This shows the detail view of the second entry, added from the browsable API. Here the field in the PUT html form shows correctly. The viewset used is quite simple. class WrongMatchViewSet(ModelViewSet): queryset = WrongMatch.objects.all() serializer_class = WrongMatchSerializer pagination_class = Pagination permission_classes = [permissions.AllowAny] And the serializer: class WrongMatchSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="wrongmatch-detail") beer_name = serializers.CharField(read_only=True, source="beer.vmp_name") current_untpd_url … -
custom pagination not woking in apiview of Django rest
I have a custom pagination class in a separate file and until now I have been importing it in a ListAPIView, but this time I tried with APIView, but it didn't work. My pagination class: class CustomPagination(PageNumberPagination): def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'page_size' : 15, 'results': data }) I am trying to use custom pagination because I can have the count of the objects as well. My view where I try to implement the pagination: from apps.products.api.pagination import CustomPagination class CouponView(APIView): permission_classes = [AllowAny] #pagination_class = CustomPagination def get(self,request,pk = None,*args,**kwargs): id = pk if id is not None: abc = Coupons.objects.get(id=id) serializer = CouponSerializer(abc) return serializer.data else: abc = Coupons.objects.all() paginator = CustomPagination() result_page = paginator.paginate_queryset(abc, request) serializer = CouponSerializer(result_page,many=True) return Response (serializer.data,status=status.HTTP_200_OK) -
how to display current booking for each room django reverse connection
i'm trying to display current booking in rooms show in my main page for admins my models.py class Room(models.Model): room_no = models.IntegerField(unique=True) some_fields = models.CharField(max_length=20,choices=my_choices) beds = models.IntegerField(default=2) #others class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,related_name='rooms') #others my views.py @login_required def all_rooms(request): rooms_show = Room.objects.all().order_by('room_no') return render(request,'rooms/rooms.html',{'rooms':rooms_show}) i need to show current booking for each rooms in my template <div class="group cursor-pointer"> <a href="{% url 'booking:add_booking' i.room_no %}"> <div class="overflow-hidden transform transition duration-400 hover:scale-90 "> <img src="{% static 'img/iconbed.png' %}" class="rounded-full w-24 mx-auto" alt=""> </div> </a> <div class="border border-gray-900 rounded-xl overflow-hidden -mt-12"> <div class="p-2 rounded-xl bglightpurple pt-12 items-center"> <div class="text-center rounded bggray text-xs md:text-base"> <p class="inline textorange "><i class="bi bi-list-ol"></i> room no:</p> <p class="inline text-white text-white">{{i.room_no}}</p> </div> <div class="grid grid-cols-2 mt-3 gap-2"> <div class="p-1 text-center text-xs rounded bggray"> <span class="text-white"><i class="bi bi-columns-gap"></i> {{i.room_type}}</span> </div> <div class="p-1 text-center text-xs rounded bggray"> <span class="text-white"><i class="bi bi-columns-gap"></i> {{i.beds}} beds</span> </div> <div class="p-1 text-center text-xs rounded bggray"> <span class="text-white">{{i.price}}</span> </div> <div class="p-1 text-center text-xs rounded"> <a href="{% url 'rooms:update_room' i.room_no %}" class=" px-3 pt-1 rounded-lg text-white bg-yellow-500"><i class="fas fa-eye"></i></a> </div> </div> </div> <!--- display booking list here--> <div class="p-1 rounded-xl text-xs mt-1 items-center"> <p class="text-white text-center">16-6-2021 - 19-6-2021</p> </div> </div> i need to … -
With format='multipart' in test client, data of nested dict been ignored or removed
I have a nested serializer containing, containing an Image Field in the nested serializer, the serializers are:- class FloorPlanLocationSerializer(serializers.ModelSerializer): class Meta: model = FloorPlan fields = ( 'floor', 'image', ) extra_kwargs = {'floor': {'required': False}, 'image': {'required': False}} class LocationSerializer(FilterSerializerByOrgManaged, serializers.ModelSerializer): floorplan = FloorPlanLocationSerializer(required=False, allow_null=True) class Meta: model = Location fields = ( 'id', 'organization', 'name', 'type', 'is_mobile', 'address', 'geometry', 'created', 'modified', 'floorplan', ) read_only_fields = ('created', 'modified') def to_representation(self, instance): request = self.context['request'] data = super().to_representation(instance) floorplans = instance.floorplan_set.all().order_by('-modified') floorplan_list = [] for floorplan in floorplans: dict_ = { 'floor': floorplan.floor, 'image': request.build_absolute_uri(floorplan.image.url), } floorplan_list.append(dict_) data['floorplan'] = floorplan_list return data def create(self, validated_data): floorplan_data = None if validated_data.get('floorplan'): floorplan_data = validated_data.pop('floorplan') instance = self.instance or self.Meta.model(**validated_data) with transaction.atomic(): instance.full_clean() instance.save() if floorplan_data: floorplan_data['location'] = instance floorplan_data['organization'] = instance.organization with transaction.atomic(): fl = FloorPlan.objects.create(**floorplan_data) fl.full_clean() fl.save() return instance With this above serialzier, it works fine with DRF Browsable page, but when I try to send the data with the test client in multipart format, the nested data gets removed while send the POST request, this is how I wrote the tests:- def test_create_location_with_floorplan_api(self): path = reverse('geo_api:list_location') coords = json.loads(Point(2, 23).geojson) image = Image.new("RGB", (100, 100)) with tempfile.NamedTemporaryFile(suffix=".png", mode="w+b") as tmp_file: … -
Django form set placeholder in CharField instead of value
Suppose I have a following simple form: class UserForm(Form): first_name = CharField(label='First Name') last_name = CharField(label='Last Name') And there is some custom validation. When a user submitted invalid data, Django renders the form with invalid values inside the fields. Is it possible to render empty CharFields but with placeholders that show the entered data? -
change django-avatar default photo
I'm using django-avatar. and I want to change the default image of the dajngo-avatar. I tried AVATAR_DEFAULT_URL="https://path-to-image.jpg" but it's not working. -
Writing query inside a model
I want to write a query where if the Complete Status is all true , complete inside model Order should be automatically true. Can i write a query inside Order model using some methods or anything ? And can you suggest some help. class Order(models.Model): customer = models.ForeignKey(Customer , on_delete=models.SET_NULL , null= True , blank = True) date_ordered = models.DateTimeField(auto_now_add = True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length= 100 , null=True) class CompleteStatus(models.Model): order = models.ForeignKey('Order', on_delete=models.SET_NULL , null=True) seller = models.BooleanField(default=False) warehouse =models.BooleanField(default=False) pickup = models.BooleanField(default=False) delivered = models.BooleanField(default=False) received_by_customer = models.BooleanField(default=False) -
Django Check constrain prevent save string in json fileld
How can I prevent saving string literal in JSON field? class MyModel(models.Model): settings = JSONField("Additional settings", default=dict, blank=True) Now I can do this inst = MyModel.objects.get() inst.settings = 'some string' inst.save() but some login expect dict. now I need check dict in code. I add simple constrain class Meta: ordering = ['-updated_at'] constraints = [ CheckConstraint( check=~(Q(settings='') | Q(settings='{}')), name='reduce_sats_process_check_settings_must_be_json_object' ) ] but this not prevent saving all string variants. -
django permissions instead of groups
We have multiple positions in the hierarchy of the company : such as director of sales, salesperson, restaurant director and let say maitre d'hotel, however if we have a follow up or a memo some might be a good fit for the whole staff to see but if the memo concern the pricing strategy of a particular quote, we don't want the maitre d'hotel to see this particular follow up, or quote, or detail in the dashboards as of now I understand that the permission system allow us to briefly avoid that tier be able to edit or delete a particular model instance from the database : should I do a attribute level of permissions such as writing a model with level 1, 2 , 3 , 4 , 5 (permissions ) and attribute one to each user and add template tags that will display a different html page or is there a better way to do it, thanks -
ElephantSQL and Django not working together, atuhentication failed
I have bumped into the following problem and still don't know how to fix it. For the record I am using mac. I would like to connect my djnago app to an elephantsql database, so I have changed the database info. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'abc', 'USER':'abc', 'PASSWORD':'password', 'HOSTS':'tai.db.elephantsql.com', 'PORT': 5432 } } I see my database working fine in pgAdmin 4, so there is no issue with that, but when I run python manage.py migrate got the following error: django.db.utils.OperationalError: FATAL: password authentication failed for user "abc" Do you have any tips how to go forward? -
issue httpresponseredirect:unable to redirect to homepage
I’m keeping getting this redirect wrong either I got the code wrong or it keeps running in an infinite loop. urls.py first app urlpatterns = [ path("",views.pomo,name="pomo"), path("agenda/",views.agenda,name="agenda"), path("notes/",views.notes,name="notes"), ] urls.py main urlpatterns = [ path('admin/', admin.site.urls), path("", include('pomofocus.urls')), path ("login/", include('accounts.urls')) ] urls.py accounts(2nd app) urlpatterns = [ path("register/",views.register_request, name="register") ] views.py from django.contrib import messages def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): #save user user = form.save() #login user login(request,user) #send success message messages.success(request,"Congrats you are registered now") return redirect(“pomofocus:pomo") messages.error(request,"Unsuccesful registration.Try again.") form = NewUserForm() return render(request,"account/registration.html",context={"register_form":form}) -
How do i store stored data in a new form?
Currently im facing a issue where this my edit webpage have to get the data out of the db and appear in a form (this form looks exactly like the add new device form page). How my add device page look like Currently for my edit page : I am able to extract the information from 2 different tables in the db and print them out on the page in a table format. But how do make it the same as my add device page. Under each textfield for my add device page, im using eg. {{forms.hostname}}. If i remove this and key in the specific key for the data in my edit page, theres no textfield and the text wont get display -
Mocking SQLite database calls for DJango ORM pytest
Below is the code from one of my django view which uses django ORM to fetch data, however running the same from pytest gives error: FAILED tests/test_views.py::TestViews::test_trendchart_view - AttributeError: 'NoneType' object has no attribute 'metricname' metrics = Metrics.objects.all() metric = metrics.filter(metricid=metric_id).first() metric_name = metric.metricname Looking at the error it seems that metric is None. Any idea how can I mock this call to return some dummy object? Below is my test case for reference: @pytest.mark.django_db class TestViews: def test_trendchart_view(self): kwargs={'event_id':1, 'ar_id':1, 'tcid':1, 'activemenu_id':1, 'metric_id':1} path = reverse('trendchart', kwargs=kwargs) request = RequestFactory().get(path) response = treandchartsummary(request,None,**kwargs) assert response.status_code == 200 -
View detailed view of model item directly in django admin
Django shows list of model items in admin panel, but don't want to show the list but I directly want to show the detail view . How can i do this ? -
Automatic id not getting assigned (Django PostgreSQL)
I am using a PostgreSQL 12 backend with Django 2.2. For one particular model of a complex project (with several apps and dozens of models), a model is not assigning the auto-incremented ID anymore. The model itself is innocuous: class SavedAnalysis(models.Model): title = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) sq = models.ForeignKey(SearchQuery, on_delete=models.SET_NULL, null=True, default=None) json = models.TextField(blank=True, default='') class Meta: unique_together = ['title', 'user'] ordering = ['user', 'title'] When I do either SavedAnalysis.objects.create(...) or create an instance and call save() on it explicitly, the id is being set to None. The object is being created correctly, only the Django-assigned AutoField "id" does not seem to increment. This exact code was working fine for a long time, but I had to move the database to a different machine recently and only this particular model seems to be affected. I suspected sqlsequencereset to be the cause but that has not helped as well. Now I am resorting to a "hack": s = SavedAnalysis(title=title, user=user, sq=q, json=j) s.save() if s.id is None: SavedAnalysis.objects.filter( title=title, user=user).update(id=SavedAnalysis.objects.order_by('-id').values_list('id', flat=True)[1] + 1) Anyone seen this before? I'd prefer that the expected behavior works rather than using a hack. -
AuthCanceled at /oauth/complete/facebook/
Request Method: GET Request URL: http://www.example.com/oauth/complete/facebook/?granted_scopes=public_profile&denied_scopes&code=AQBoM1W9l8X1lnsYCaspOQVi1nxYG1Vh3IDkdXOw1dcW5tG6dNfjzbrQ0APZlpIquhjdeMLsQ6Wd_vktM_7pCv2GI-Uqsvya7iVm7jdnX2nbaMPkF2f7JgznpVZLh5oRXQv2AvG0Syu-GZ4skYp2ZVDNvuWdfEu-OnpN_d0GsY-P07BwwsCIlIwL6CrR0GCjNK3_wSC4c8BTWXS9fPeKd7rQOZB863x9wEwVQDjCx-LgxL41_rGJlIbk01pFWPCze5GZvsFJe8xAvbzjO9E1Jrq6KGf2pddF4-78q3xLz-IG3Ary31DoSHS2POmb-KrPvMQvK96ouft-vUBUFcoEe83P&state=nTPuVRtqNf8wSmU9SiFRYozizutSAoAd Django Version: 3.2.5 Python Version: 3.8.10 Installed Applications:[ 'admin_interface', 'colorfield', 'carparking.apps.CarparkingConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django' ] Installed Middleware:[ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware' ] Traceback (most recent call last): File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/utils.py", line 248, in wrapper return func(*args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/backends/facebook.py", line 97, in auth_complete response = self.request(self.access_token_url(), params={ File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/backends/base.py", line 238, in request response.raise_for_status() File "/home/pratik/myproject/env/lib/python3.8/site-packages/requests/models.py", line 953, in raise_for_status raise HTTPError(http_error_msg, response=self) During handling of the above exception (400 Client Error: Bad Request for url: https://graph.facebook.com/v8.0/oauth/access_token?client_id=819143458788732&redirect_uri=http%3A%2F%2Fwww.carparking.site%2Foauth%2Fcomplete%2Ffacebook%2F&client_secret=4c2c5ed7bf2e5911aaa3bb7f44b73688&code=AQBoM1W9l8X1lnsYCaspOQVi1nxYG1Vh3IDkdXOw1dcW5tG6dNfjzbrQ0APZlpIquhjdeMLsQ6Wd_vktM_7pCv2GI-Uqsvya7iVm7jdnX2nbaMPkF2f7JgznpVZLh5oRXQv2AvG0Syu-GZ4skYp2ZVDNvuWdfEu-OnpN_d0GsY-P07BwwsCIlIwL6CrR0GCjNK3_wSC4c8BTWXS9fPeKd7rQOZB863x9wEwVQDjCx-LgxL41_rGJlIbk01pFWPCze5GZvsFJe8xAvbzjO9E1Jrq6KGf2pddF4-78q3xLz-IG3Ary31DoSHS2POmb-KrPvMQvK96ouft-vUBUFcoEe83P), another exception occurred: File "/home/pratik/myproject/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/pratik/myproject/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_django/utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_django/views.py", line 31, in complete return do_complete(request.backend, _do_login, user=request.user, File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/actions.py", line 45, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/backends/base.py", line 40, in complete return self.auth_complete(*args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/utils.py", line 251, in wrapper raise AuthCanceled(args[0], response=err.response) Exception Type: AuthCanceled at /oauth/complete/facebook/ Exception Value: Authentication process canceled I think this error because of it … -
Jupyter runtimeerror
How can I solve this error? seis_model = Model(vp=reshaped, origin=(0., 0., -1000.), spacing=(10., 10., 10.), shape=shape, nbl=30, space_order=4, bcs="damp") RuntimeError: Couldn't find libc's posix_memalign to allocate memory -
Django: Can't save image from template
If I try to save image from admin site, it works properly. But I'm trying to save image from template, and its not working. here is my code models.py: class About(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profilePicture = models.ImageField(upload_to='images/profile/', default = 'images/useravater.png') views.py: def editProfile(request): if request.method == 'POST': profilePicture = request.FILES['pp'] About.objects.filter(user=request.user).update(profilePicture=profilePicture) # more code... html: <form style="width: 100%;" action="/editProfile/" method="POST" enctype="multipart/form-data">{% csrf_token %} <input id="inputpp" type="file" accept="image/*" name="pp" title="Select Image"> <!-- more code --> </form> after running this code, if i try to print: print(About.objects.get(user=request.user).profilePicture.url) it shows: Not Found: /media/image_name.jpg can you please find my problem? how do I save image to /media/images/profile/? -
How can I exclude entries if the max of my JSON Field values is 0?
I have this kind of JSON Field called fieldA : `{'test': 0, '1': 0, 'number': 0} And I would like to exclude if the max of the values is 0. I thought to use that if A is my query using Django ORM : A.exclude(fieldA ? Then I don't know how can I do this ... Could you help me please ? Thank you ! -
How to get the data from views to template Django
From my model I am uploading a file , In my views I perform some operations on the file .I am using DetailView of CBV of Django , In which I get one object and perform some operations on it . Now I want the data (after performing the operations) in my template . I know how to show the file in my template because the file is in models . But the functions are not in models and I want to print those in my template. My models.py is : class FileUpload(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True , null=True) file = models.FileField(upload_to='files') def get_absolute_url(self): return reverse('home') my views.py is : class PostDetailView(DetailView): context_object_name = "object_list" template_name = "post_detail.html" def get_object(self, *args,**kwargs): request = self.request pk = self.kwargs.get('pk') instance = FileUpload.objects.get(id = pk) #I want to print this instance if instance is None: raise Http404("File Does not EXIST") else: pdfFileObj = open(instance.file.path, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) print('number of pages = ',pdfReader.numPages) pageObj = pdfReader.getPage(0) print(pageObj.extractText()) #I want to print this query = pageObj.extractText() for j in search(query, tld="co.in", num=10, stop=10, pause=2): print(j) #I want to print this pdfFileObj.close() return instance -
Cannot Edit Form in Javascript With Django
I'm trying to edit a form on this site with Django, and save the edits using Javascript (but not mandating a page refresh). When the user clicks 'edit' on the page, nothing happens. No console errors. I think the issue is in the Javascript function edit_post. I'm new to using Javascript with Django. Any help is appreciated. Relevant urls.py path('edit_post/<str:id>', views.edit_post, name="edit_post"), #before was pk not id path('edit_post/', views.edit_post), path("profile/<str:username>", views.profile, name="profile"), Javascript function edit_handeler(element) { id = element.getAttribute("data-id"); document.querySelector(`#post-edit-${id}`).style.display = "block"; document.querySelector(`#post-content-${id}`).style.display = "none"; // everything above this works and opens up the form for editing edit_btn = document.querySelector(`#edit-btn-${id}`); edit_btn.textContent = "Save"; edit_btn.setAttribute("class", "text-success edit"); if (edit_btn.textContent == "Save") { edit_post(id, document.querySelector(`#post-edit-${id}`).value); //here edit_btn.textContent = "Edit"; edit_btn.setAttribute("class", "text-primary edit"); }} function edit_post(id, post) { const body = document.querySelector(`#post-content-${id}`).value; fetch(`/edit_post/${id}`, { method: "POST", body: JSON.stringify({ body:body }) }).then((res) => { document.querySelector(`#post-content-${id}`).textContent = post; document.querySelector(`#post-content-${id}`).style.display = "block"; document.querySelector(`#post-edit-${id}`).style.display = "none"; document.querySelector(`#post-edit-${id}`).value = post.trim(); }); } Relevant html <span id="post-content-{{i.id}}" class="post">{{i.text}}</span> <br> <textarea data-id="{{i.id}}" id="post-edit-{{i.id}}" style="display:none;" class="form-control textarea" row="3">{{i.text}}</textarea> <button class="btn-btn primary" data-id="{{i.id}}" id="edit-btn-{{i.id}}" onclick="edit_handeler(this)" >Edit</button> <br><br> views.py def edit_post(request, id): post = Post.objects.get(id=id) form = PostForm(instance=post) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return JsonResponse({}, status=201) else: …