Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST request return 405 on auth (nginx angular)
i'm using django and angular with nginx. I get 405 not allowed when i try to post to /auth/. my nginx conf: server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /home/dev/projet-name/frontend/my-app/dist/tryangular; include /etc/nginx/default.d/*.conf; location / { try_files $uri $uri/ /index.html; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } location ~ ^/(api|admin)/ { include uwsgi_params; uwsgi_pass SERV_IP:3031; } } Djnago is on the same server. I don't even know where i messed up -
Disable CSRF validation on Wagtail Page
I'm trying to do a curl POST request on a wagtail page. Unfortunately I hit the CSRF protection. I tried to disabled CSRF on this specific type of page using the @csrf_exempt decorator, without success. Here is my pseudo code (one of many attemps): @method_decorator(csrf_exempt, name='serve') class NewsletterPage(MedorPage): class Meta: verbose_name = _("newsletter page") Seems like the csrf verifition is done even before the serve method is called. Any idea? thanks -
Counting the many-to-many value in filter
I am trying to do like this my class is here class TweetJson(models.Model): authors = models.ManyToManyField(Station) and filter MyText.objects.filter(Q(authors__count__gte=1)) However it returns. Related Field got invalid lookup: count is there any way to count the number of many-to-many objects? -
The value in __init__ doesn't returns correct value?
I have a model in django: class Game(models.Model): gaming = models.BooleanField(default=False) def __init__(self, *args, **kwargs): super(Game, self).__init__(*args, **kwargs) self.old_gaming = self.gaming Now, when I print the value of self.old_gaming it comes out to be True instead of False while working from an application. Whereas, while I work on django-admin it shows False. Why is it showing two different values? -
Django - How to get the object attribute before updating in Update class based view?
I'm learning Django and I'm struggling with the Class Based View of Django. I would like to access the object attributes before the update in order to show the user what was the previous attributes. Here my class view : class GroupUpdateView(LoginRequiredMixin, UpdateView): model = GroupName fields = ['name', 'description'] template_name = 'dashboard/groups/group_update_form.html' group_name_before_editing ="" #I wanted to write model.name here #Overrive def form_valid(self, form): return super().form_valid(form) def get_success_url(self): messages.success(self.request, "The group %s was updated successfully" % ( self.group_name_before_editing)) return reverse_lazy('dashboard:group-update', args=(self.object.pk,)) In get_success_url(), I would like to show the user the previous name of the group that has been updated. I tried also with the get_context_data() but was not able to obtain the result. Could you help please ? How to get the current model attributes ? -
Django search : query multiple table, join them then return the queryset
I'm building a search for my product price tracking app and there're 2 models products and scans class products(models.Model): product_id = models.IntegerField(primary_key=True) product_name = models.CharField(max_length=100) product_link = models.CharField(max_length=255) image_link = models.CharField(max_length=100) store_name = models.CharField(max_length=100) class Meta: verbose_name_plural = "products" def __str__(self): return str(self.product_name) class scans(models.Model): scan_id = models.IntegerField(primary_key=True) prod_id = models.IntegerField(models.ForeignKey("scrape.Model", on_delete=models.CASCADE)) price = models.IntegerField() scanned_time = models.DateTimeField(default=timezone.now) class Meta: verbose_name_plural = "scans" def __repr__(self): return str(self.prod_id) the search is supposed to take a name(string) input and query for a store name in the same table and query for price which is in another table and return the query set with the product_name, store_name and price. I've tried this class searchResults(ListView): model = 'products', 'scans' template_name = 'result.html' # let query = GET request from form (in home.html) def get_queryset(self): queryset = [] rawquery = self.request.GET.get('q') queries = rawquery.split(" ") for q in queries: prodresults = products.objects.filter( Q(product_name__icontains=q) ).distinct() for prodresult in prodresults: prod_id = products.objects.get(product_name=prodresult).product_id prod_price = scans.objects.get(prod_id=prod_id).price for result in prodresults: #joins results toegther queryset.append(result) queryset.append(prod_price) return list(set(queryset)) The code broke at prod_price = scans.objects.get(prod_id=prod_id).price with scans matching query does not exist. -
django-autocomplete-light add parameter to query url (in version 3.3)
I'm using django-autocomplete-light in a django admin change_form.html page, however I need to change dynamically the GET parameters of the URL depending on another field. I have already tried to replicate this answer django-autocomplete-light add parameter to query url, but failed since I am using version 3 Tried this way: $("#id_city").change(function(){ url = '{% url "custom-pop-autocomplete" %}'; $('#id_p').attr('data-autocomplete-light-url', url + `?city=${$(this).val()}`); $('#id_p').trigger('autocompleteLightInitialize'); }); This way: $('[data-autocomplete-light-function=select2]:not([id*="__prefix__"])').each(function() { $(this).initialize }); and this way: $('[data-autocomplete-light-function=select2]:not([id*="__prefix__"])').each(function() { window.__dal__initialize(this); }); None of them working to reinitialize django-autocomplete-light. I just need to change the URL. -
Django DeprecationWarning Use of .. or absolute path
I am getting a lot of these warnings in production but not on devstack which is making me curious to know about this warning and how to get rid of this. Apparently there is no information which imports is causing the issue. I am looking for any tools, documentation that explains this Deprecation warning when this will raise an exception in the future and steps to get rid of this warning. thank you! [__init__.py:1566] - /edx/app/edxapp/venvs/edxapp/lib/python3.5/site-packages/pkg_resources/__init__.py:1158: DeprecationWarning: Use of .. or absolute path in a resource path is not allowed and will raise exceptions in a future release. -
Insert Data From HTML to Django Template
I want to save data from HTML template into database Model. I want to override this toplaner_name, toplaner_avatar, toplaner_price everytime I submit the Form. The img and span tags are dynamically changing by JS template <form method='POST'> {% csrf_token %} <div class="player-on-map toplaner"> <img class='img-on-map' src="{% static 'images/ago/img1.png' %}" alt="portrait-on-map"> <span class="nickname">Szygenda</span> <span>Price: 1500</span> </div> <button type='submit'>SAVE TEAM</button> </form> models.py class Team(models.Model): toplaner_name = models.CharField(max_length=30, default='Ibo') toplaner_avatar = models.ImageField(default='avatar.png') toplaner_price = models.IntegerField() JS toplaners.forEach(toplaner => toplaner.querySelector('.btn').addEventListener('click', function(){ toplaner_on_map.innerHTML = toplaner.innerHTML; toplaner_on_map.querySelectorAll('.btn, .position, .player-price').forEach(item => item.classList.add('hide')) })) -
How to support django data migration in a plugin design
I'm trying to implement a plugin design pattern in a django app to dynamically extend the app functionality. Everything looks routine: I'm gonna have a parent abstract class/interface and each plugin implements the required methods and registers itself to the plugin manager... But, each plugin may need it's specific database models to work with. I have no idea how to implement it through plugin pattern. Any workaround to provide django db migrations dynamically? -
How to export a model with images to an excel in Django?
I have a model which it contains some data and a ImageField in my Django project and I want to export them to an excel with images. How can I do that? -
How do you compare today's date with the date provided by Django using JavaScript/JQuery?
The whole problem is to compare the date extracted from the database and passed to the input field in the template with today's date generated by jquery. Unfortunately when I tried print el console return me "undefined value" What I created so far: <input type="date" class="date" hidden data-book="{{ book.slug }}" value="{{ book.date|date:"Y-m-d" }}"> $( document ).ready(function() { let endDt = new Date(); $(".date").each(function () { let el = $(this).attr('data-book').val; if( (new Date(startDt).getTime() < new Date(endDt).getTime())) { // Rest of code here } }); }); -
how can i edit instance of the Project class in the Django shell after i created
i created an entry in my projects table and saved it to the database with django shell but i want to customize my entry after i created what should i do ? >>> p1 = Project( ... title='My FirstProject', ... description='Another web development project.', ... technology='Flask', ... image='img/project1.png' ... ) >>> p1.save() >>> p2 = Project( ... title='My Second Project', ... description='A final development project.', ... technology='Django', ... image='img/project2.png' ... ) >>> p2.save() -
multiple aspect filter in abay sdk
response = api.execute('findItemsAdvanced', {'keywords':'Macbook', }, 'aspectFilter':[{'aspectName': 'Series','aspectValueName': 'MacBook Air'}, {'aspectName': 'Processor', 'aspectValueName': 'AMD A10'}] }) Now i am working in ebaysdk . i am facing the problem with multiple aspect filter. Is there any solution for multiple aspect filter.if aspect filter is single it is working fine but multiple are not -
DRF: testing POST method using Client()
I have a class that accepts the dictionary list - data = [{}, {}] . If I send data via Postman, everything will work but the problem with testing POST class method. The error is FAIL: test_vendor_from_csv_create (vendors.tests.VendorCsvCreateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/y700/projects/solution/apps/vendors/tests.py", line 128, in test_vendor_from_csv_create self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 404 != 200 views.py class CsvToDatabase(APIView): def post(self, request, format=None): r_data = request.data for data in r_data: if data['nda'] == '': data['nda'] = None ... #some logic serializer = VendorsCsvSerializer(data=data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) test.py class VendorCsvCreateTest(APITestCase): #API def test_vendor_from_csv_create(self): url = reverse('csv_vendor_create') response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) I assume the problem is format='json'. If this is the case, how do I transfer the data in the right format? If the reason is different, can you give me a solution, please! -
Redirect to item page after deleteView in class based views
I have an invoice page with each invoice (factuur) has items in it (relation invoice-items with ForeignKey). When I delete one of the items with the class based deleteView I want to redirect back to the specific invoice id with the remaining items in it. urls.py: path('factuur/<factuur_id>', views.facturen_detail_view, name='facturen_detail_view'), path('delete/<int:pk>', views.FactuurItemDeleteView.as_view(), name='delete_factuurItem'), views.py: class FactuurItemDeleteView(BSModalDeleteView): model = FactuurItems template_name = 'delete_fitem.html' success_message = 'Succes: factuur item is verwijderd.' success_url = reverse_lazy('facturen_detail_view') So what I want is redirect it to /factuur/factuur_id after deletion (where I was at the moment of clicking the delete button). But how do I redirect as I need to know invoice id (factuur_id) in the first place. I don't know how to do this with the class based views method. When success_url is as above then it tries to redirect to the factuur_id with the deleted item_id what is not the wanted situation. -
page not found error while passing paarmeter through url in view django
I am new to python django. I am facing an issue while passing parameter to view through URL in django. code: views.py from django.shortcuts import render from django.http import HttpResponse def hello(request): text = "HEllo" return HttpResponse(text) def viewArticle(request, articleId): text = "HEllo : %d"%articleId return HttpResponse(text) urls.py from django.conf.urls import url from django.urls import path,include from myapp import views urlpatterns = [ path('hello/',views.hello,name='hello'), path('article/(\d +)/',views.viewArticle,name='article'), ] image: -
Django Base Validator
i need to make a regex for my django project. I've made a Custom Validator that must implement a regex. I need to implement a regex that check the format of this different input: nnnn-nn/yyyy or nnnn/yyyy in the first input the number after - must 1 or 2 long -
Django Error during template rendering: maximum recursion depth exceeded while calling a Python object
I don't understand where I stucked -
How to make stripe Charge amount dynamic in Django
I am new to Django, I am trying to build a hostel reservation with stripe payments.I have a room model and Reservation as follows. class Reservation(models.Model): student = models.OneToOneField(User,on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete = models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) class Room(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200,null=True,blank=True,unique=True) price = models.IntegerField() hostel = models.ForeignKey(Hostel,on_delete=models.CASCADE,null=True) number_of_beds = models.IntegerField() room_thumbnail = models.ImageField(null=True) resized_thumbnail = ImageSpecField( processors=[ResizeToFill(620, 430)], format='JPEG', options={'quality': 60}) room_type = models.ForeignKey(Category,on_delete=models.CASCADE) room_number = models.IntegerField() is_reserved = models.BooleanField(default=False) description = models.TextField() def get_absolute_url(self): return reverse('room_detail', args =[ str( self. id)]) I also have a room detail view for the rooms and charge view where ai want the charge amount on stripe to be dynamic based on the price of the rooms. Can some help me on how to solve this. <!-- begin snippet: js hide: false console: true babel: false --> def BookingConfirmation(request): if request.method == 'POST': rooms = Room.objects.all() amount = rooms.price charge = stripe.Charge.create( currency='usd', amount = amount, description='A Django charge', source=request.POST['stripeToken'] ) return render(request,'booking-confirm.html',{}) def RoomBookingView(request,pk): publishkey = settings.STRIPE_PUBLISHABLE_KEY if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) student_id = request.user room_id.is_reserved = True, reservation = Reservation( room_id = room_id.id, student_id = student_id.id, ) reservation.save() try: room = … -
Using FPDF i want Inline bold text in paragraph in python
from fpdf import FPDF pdf1 = FPDF pdf1.multi_cell(0, 5, 'This is my disclaimer. THESE WORDS NEED TO BE BOLD. These words do not need to be bold.', 0, 0, 'L') pdf1.output("sample.pdf") -
how to fetch data in chunks from db in django and then delete them?
My basic problem statement is that I want to fetch every row but in chunks only 2000 rows at one time from a table having 1 million rows. And after these chunked queries are evaluated i want to delete every row. so just say i have a = Model.objects.filter(id=1<2000) b = Model.objects.filter(id=2000<4000) c = Model.objects.filter(id=4000<6000) .. .. now if i combine all these queryset into one queryset by some means say del = a + b + c +d ...... and i do del.delete() so will it delete all the rows in less time or it will re process queries again to delete them and will take time? -
Django url dispatcher calls the wrong function
the problem that I have is this one: I created a new re_path in my urls.py file, but when I make a request at that url the wrong function is called. # myapp/urls.py from django.urls import path, re_path from . import views as multiplayer_lite_views urlpatterns = [ # other paths re_path(r'vote/(?P<match_id>\w{16})', multiplayer_lite_views.vote, name='multiplayer_lite_vote'), re_path(r'nightvote/(?P<match_id>\w{16})', multiplayer_lite_views.night_vote, name='multiplayer_lite_night_vote'), path('new-match/', multiplayer_lite_views.new_match, name='multiplayer_lite_new_match'), path('', multiplayer_lite_views.home, name='multiplayer_lite_home'), ] what I did was simply duplicate the line re_path(r'vote/... and renamed it to re_path(r'nightvote/... but changing also all the other info, like multiplayer_lite_views.vote to multiplayer_lite_views.night_vote. The problem is that when I go to this url nightvote/ the function vote is called. # myapp/views.py def vote(request, match_id): print('vote function') # do other stuff return return JsonResponse(...) def night_vote(request, match_id): print('nightvote function') # do other stuff return return JsonResponse(...) In the server side what I see is that: ... vote function [18/Mar/2020 10:19:16] "POST /nightvote/gfvkpvhlwlqzosae HTTP/1.1" 200 16 ... PS I have already tried to close Django and reopen, the same with vs code. -
implementing like system in django and postgres
i want to implement a like system for our project,my question is almost about performance,i want to use django with Postgresql DB,in models.py i have a Like model: class Like(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name = "like") place = models.ForeignKey(Places,on_delete=models.CASCADE,related_name = "likedPlace") when a user want to see a post,i should show them if he/she liked the post or not,is postgresql good for this purpose?or any other relational database?if i have 50000 user and each user like 10 post,each time i should iterate 500000 row in worst case. can i use nosql database like cassendra for this purpose? -
How to add additional field in the default admin_User table in Django 3.0.3
I don't have idea to put extra field in default admin user table/ model in django 3.0.3 version . Please give some idea to make extra field like user_roll, user_id, designation etc.