Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to search string in children categories of parent?
I want to search 'query' in every children and render results to list.html. I couldn't find the solution so I decided to ask here. Here is my code: def search_query_string(request, path=None, instance=None): query = request.GET.get('query', False) category = request.GET.get('category', False) if category: cat = get_object_or_404(Category, name=category) children = cat.get_descendants(include_self=False) ads = None if query: if category: ads = Ad.objects.filter(Q(name__icontains=query) ) # I want to search query in children here return render_to_response('ads/list.html', locals(), context_instance=RequestContext(request)) ads = Ad.objects.filter(Q(name__icontains=query)) return render_to_response('ads/list.html', locals(), context_instance=RequestContext(request)) As you can see I already have the list of children categories, but still don't know how to search in them. Please help :( -
What is the problem with web crawl for-loops?
I am going to crawl the web with python and selenium. You attempted to crawl a loop with 500 operations to fetch 4 elements from a single line. The three elements will crawl without problems, but one element will stop with a 'no such element' error message during the loop. Below is the code I wrote. What's wrong? The page you want to crawl is a good access to the queryselector from Google Developer Tools. I will try for various days and try various things and ask for help. for i in range(0, review_page_count - 1): if i is not (review_page_count - 2): driver.find_element_by_xpath('//div[@id="south"]/div/nav/div/ul/li/a[contains(text(), "{}")]'.format(i+1)).click() time.sleep(5) if i > 0: driver.find_element_by_xpath( '//div[@row="{}"]/div[@colid="productName"]/a'.format(j)).send_keys(Keys.CONTROL + Keys.HOME) for j in range(0, 500): if j is not 0 and j % 4 is 0: driver.find_element_by_xpath( '//div[@row="{}"]/div[@colid="productNo"]/a'.format(j)).send_keys(Keys.PAGE_DOWN) product_num = driver.find_element_by_xpath('//div[@row="{}"]/div[@colid="productNo"]/a'.format(j)).text product_name = driver.find_element_by_xpath('//div[@row="{}"]/div[@colid="productName"]/a'.format(j)).text score = driver.find_element_by_xpath('//div[@row="{}"]/div[@colid="reviewScore"]'.format(j)).text review_content = driver.find_element_by_xpath('//div[@row="{}"]/div[@colid="reviewContent"]/a'.format(j)).get_attribute('text') review_date = driver.find_element_by_xpath('//div[@row="{}"]/div[@colid="createDate"]'.format(j)).text print(j) print(product_num, product_name, score, review_content, review_date) when get review_content row=126 caused ERROR plz help me! thx -
Calling time consuming method inside django view without using task queue
Whenever there is time consuming logic in django view I run that as background task using celery and return response. from my_app.task import long_task import json def my_view(request): body = request.body body = json.loads(body) key = body['key'] long_task.delay(key) # This will run in background return JsonResponse({'message': 'request submitted'}) Is there any way to achieve this behaviour to call long_task method without any background task queue like celery etc so I can quickly send response to user? -
PDFKit ignores Bootstraps h-100 for cards
So I have a view (in Django) that looks like this: when viewed as a view in the Browser. But when PDFKit renders it it looks like Note the bottoms of the cards are not level - this is the issue. For anyone who doesn't know the h-100 class looks like: .h-100 { height: 100%!important; } The code used to produce the PDF is: def invoice_download(request, invoice_id): try: #Get the invoice and render it as a string. invoice = BusinessInvoice.objects.get(pk=invoice_id) padcount = [None] * int(8 - invoice.businessinvoiceitem_set.count()) context = {'invoice': invoice, 'padcount': padcount, 'site_url':settings.SITE_URL } html = render_to_string('business/invoice_print.html', context, request) #Build the filename the_date = invoice.date.strftime('%Y-%m-%d') filename = "INV%03d-%s-%s.pdf" % (invoice.id, invoice.client, the_date) filename = "".join(filename.split()) fullFilePath = settings.MEDIA_ROOT + 'invoices/' + filename #Make the pdf and save to fullFilePath pdfkit.from_string(html, fullFilePath) #Return the PDF as a file to Django/View response = FileResponse(open(fullFilePath, 'rb')) except BusinessInvoice.DoesNotExist: raise Http404("Something went wrong?") return response Is this something I can overcome or am I just going to lose the card borders? -
can i use python 3.7 with Django for production
I want to use django channels, apache(modwsgi),redis , are these features are supported in 3.7. I have this problem since I want to use these features for production as well be updated with the support and also performance -
Django ImportError: cannot import name 'settings' only when running manage.py test
I'm new to Django and recently inherited a project that has two main apps (my_app and my_soc_app), and has a directory structure similar to the one shown at the end of the post. I'm trying to run the project's tests, and when I run python manage.py test, the tests under the main app my_app all run fine, but when it tries to run the tests under my_soc_app run, it fails while trying to do from my_soc_app import settings with the error shown below. I can't figure out why it complains about that import ONLY when I'm trying to run the tests. The imports in my_app/my_soc_app/my_soc_app/soc_app1/tests/test_soc_app1.py are: import asyncio from unittest import TestCase, mock from uuid import uuid4 import aioredis import asyncpg from aiohttp.test_utils import setup_test_loop, unittest_run_loop from my_soc_app import settings from my_soc_app.auth.user import User from my_soc_app.services import Tracking Error Output And the error I get when I run python manage.py test my_soc_app is: $ python manage.py test my_soc_app Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: my_soc_app.my_soc_app.soc_app1.tests.test_soc_app1 (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: my_soc_app.my_soc_app.soc_app1.tests.test_soc_app1 Traceback (most recent call last): File "/usr/lib/python3.6/unittest/loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "/usr/lib/python3.6/unittest/loader.py", … -
How to Dynamically Add the one or more attribute(FIELD) value of one model to Another model in same app
I Want to get user and assessment from TestUsers Model (username, Assessment) to AssignmentAssessment Model (user, assessment) respectively, whenever an instance of TabletUser is created. Never Mind The indentation its fine class TabletUsers(models.Model): firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) username = models.CharField(max_length=200, unique=True) password = models.CharField(max_length=200) paassword = models.CharField(max_length=200) District = models.ManyToManyField(District) Assessment = models.ManyToManyField(MasterAssessmentType) def __str__(self): return self.firstname + self.lastname class AssignedAssessment(models.Model): user = models.ForeignKey(TabletUsers, on_delete=models.CASCADE) assessment = models.CharField(max_length=200) def __str__(self): return str(self.user) -
didn't return an HttpResponse object. It returned None instead Python
i have problem when i want edit my post. when i press edit - i have this problem ValueError at /post/19/edit/ The view blog.views.post_edit didn't return an HttpResponse object. It returned None instead. urls.py url(r'^post/(?P<pk>\d+)/edit/$', views.post_edit, name='post_edit'), views.py def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, request.FILES, instance=post) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'blog/post_edit.html', {'form':form}) post_edit.html {% block content %} <h1>Edit Post</h1> <form method="post" class="post-form" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} -
select unique rows based on single distinct column - Django
I want a unique row based on timesheet_users. But now the problem is that it is only displaying timesheet_users values in template. And even if i add other fields in `values('...', '...',....) then select unique row does'nt work. TimesheetEntry.objects.filter( timesheet_jobs__job_company = self.request.user.userprofile.user_company ).values( 'timesheet_users' ).distinct() Models.py class TimesheetEntry(models.Model): timesheet_users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users') timesheet_jobs = models.ForeignKey(Jobs, on_delete=models.CASCADE,related_name='timesheet_jobs') timesheet_clock_in_date = models.DateField() timesheet_clock_in_time = models.TimeField() timesheet_clock_on = models.DateTimeField(auto_now_add=True) timesheet_clock_in_by = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_user_clock_in_by') -
list_display and list_filter for the maximum of a one-to-many relationship
Django 1.11.13 class Contract(models.Model): title = models.CharField() class Enddate(models.Model): contract = models.ForeignKey(Contract) date= models.DateField() A contract can have multiple end dates. In the list view of the contracts in django admin I try to display a column with the latest/max date: def get_enddate(self, obj): return Enddate.objects.filter(contract_id=obj.id).aggregate(Max('date'))['date__max'] Which works, but the column is not sortable. I don't know how use admin_order_field in this instance. In addition I want to create a list_filter in conjunction with DateRangeFilter to filter contracts based on the max(date) of enddate. Similar main problem applies here. Any ideas? Thank you very much. -
How to wait for results from a celery task in Django
I have a celery task which sends data to another service. I have added the celery task send_inventory_request into RequestSupplyStock class based view. when I make a post I should first get results from celery task and then continue and return a response. I would like to first wait for the result from celery task and then return response from the post method which is the proper way to achieve this. @app.task def send_inventory_request(payload,token): auth = {'authorization':token} HEADERS.update(auth) url = PROCUREMENT_SUPPLY_STOCK_REQUESTS_URL res = requests.post(url,json=payload,headers=HEADERS) inventory_request_data = res.json() x= logger.info('Supply Stock Request {0} + {1}'.format(payload,token)) print(x) return inventory_request_data View class RequestSupplyStock(generics.CreateAPIView): def post(self, request, format=None): ........ send_inventory_request.delay(payload,get_token(request)) ......... return Response(status=status.HTTP_201_CREATED) -
Moving settings.py out of django project, how to set up to make it in work correctly?
1 my project direction structure: ├── project_one ├── conf ├── dist ├── logs ├── backend_server ├── front_web ├── logs ├── uwsgi.sh └── venv3.5 2 backend_server is my Django project: ├── backend_server ├── app1 ├── app2 ├── manage.py ├── README.md ├── requirements.txt ├── backend_server ├── templates └── utils Now I want to move backend_server.settings.py into confdirection for convenience. 3 conf/uwsgi.ini: chdir=/home/rookie/project_one/backend_server module=backend_server.wsgi enable-threads=True ... http=0.0.0.0:port 4 bacnend_server.wsgi.py import os import sys from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend_server.settings') application = get_wsgi_application() when i use uwsgi to start my project, it failed and i'm not sure how to correct this error. can you help me about this? greate thanks. -
Django CSRF Cookie Not Set error, after billing
I'm getting CSRF Cookie not set error after the user makes a purchase on the website using debit cards. PS: Not getting the error while using net banking and other payment methods. Tried adding csrf_exempt, csrf_required, csrf_ensured etc to the view. def subscription(request): if subscription_check(request.user): return redirect('all_magazines') if request.method == 'POST': payment_details = {'status': 'created',} try: payment_details = settings.RAZORPAY_CLIENT.payment.capture(request.POST['razorpay_payment_id'], str(settings.SUBSCRIPTION_AMOUNT)) except: pass if payment_details['status'] == 'captured': request.user.paidSubscriber = True request.user.startDate = datetime.now().date() request.user.endDate = datetime.now().date() + relativedelta(years=1) request.user.save() SubscriberDetails.objects.create(subscriber=request.user, fullname=request.POST['fullname'], phone=payment_details['contact'], addressLine1=request.POST['address_1'], pincode=request.POST['pincode'], email=payment_details['email'], paymentId=payment_details['id'], addressLine2=request.POST['address_2'], city=request.POST['city'], state=request.POST['state']) mail_subject = 'Payment Successful' send_mail(request.user, request.user.email, mail_subject, 'payment_success.html') else: mail_subject = 'Payment Failed' send_mail(request.user, request.user.email, mail_subject, 'payment_failed.html') return redirect('all_magazines') context = { 'name': request.user.first_name + " " + request.user.last_name, 'email': request.user.email, 'amount': settings.SUBSCRIPTION_AMOUNT, 'display_amount': settings.SUBSCRIPTION_AMOUNT//100, 'razorpay_key_id': settings.RAZORPAY_API_KEY, } return render(request, 'payment_form.html', context) -
Embedding opencv video into django website
I am working on a computer vision program that opens a cctv camera and detects objects in the frame. For the UI i am using django to create a web application. The web app contains a button which when pressed starts a live stream. While this works fine, the live stream is opened in a new window. Is there any way to embed the live stream onto the website? for example running a video in a html web page by using the video tag I looked online but could not find a proper answer to my problem. Please help me Thanks in advance -
How can i log into a website with different accounts in one browser window?
I am developing a Python Web Project, here is the question: I have logged in my site, when I try to log another account in, the first account will be covered and log out. So, how to solve this? -
takes_context=True with a template tag: why is context a RequestContext instead of a dictionary?
I have many custom tags taking context: @register.assignment_tag(takes_context=True) @register.simple_tag(takes_context=True) For example: @register.assignment_tag(takes_context=True) def get_items(context): return context['obj'].items.all() But apparently that context object is not a dictionary like the one returned by view.get_context_data, but instead context is a RequestContext object which is more of a list of dictionaries with some entries and nested data. The context data is buried in there in some nested structure, but I have no idea how to access it. Why is context a RequestContext instead of a dictionary of data, just like the docs suggest? How can I access my context data in my custom tags then? -
django post_save() signal to register new user
Below is the createprofileview class-based view to register a new user and also to create the profile of that user at the same time. class CreateProfileView(CreateView): model = Profile def post(self, request): user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST, request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() return HttpResponseRedirect(reverse('home', args=[])) messages.warning(request, 'Something went wrong in Venter, please try again') def get(self, request): user_form = UserForm() profile_form = ProfileForm() return render(request, './mysite/registration.html', {'user_form': user_form, 'profile_form': profile_form}) I have used post_save() signal along with my Profile model as follows: class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key = True ) organisation_name = models.ForeignKey( Organisation, on_delete= models.CASCADE, null=True, ) profile_picture = models.ImageField( upload_to='Organisation/Employee Profile Picture/%Y/%m/%d/', null=True, blank=True, ) phone_number = models.CharField( blank=True, max_length=10 ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() However, the user gets created and saved, but its profile details do not get saved. I am unsure how to tweak the signals function suitable to my requirements of registering a new user and also creating their profile at the same time. Please help! Thanks. -
What should be the directory structure for a REST API in Django?
I am starting with developing REST API's with the Djano framework. Previously I have worked extensively with Java related frameworks specifically with SpringBoot. If I take an example of a REST API in Java based framework below is the directory structure that I have mostly used : So something mostly on the lines of a MVC Design Pattern. Also in java mostly each class is written on a new file, however the tutorials that I have been looking around writes multiple classes within one file, is this the best practice around Django? Also I see that in Django we create a project and then inside it we create an app. Are these app equivalent of package in java? Also, in SpringBoot and other java related frameworks we normally follow a Top-Down approach, where a Controller recieves a call which is further passed on to the Service where all business logic resides which then further calls DAO(Repository) for CRUD and the corresponding result is passed from DAO to Service back to Controller which generates the formatted response. What I have moslty seen in Django is all the logic is written on views which calls Model for CRUD. Don't we follow SOLID … -
PDFs in Django with WeasyPrint and BootStrap
I can't believe this is so difficult. I'm producing a Invoice PDF in Django where the themes are styled using Bootstrap 4. Currently its outputting like this snippet - all squashed to one side. I don't believe the Bootstrap doesn't play well statement I found in another question. I have tried using wkhtmltopdf with a variety of Python wrappers but run into problems earlier in the process - at least Weasy gives me a PDF! Its clearly got the style but why is it squashing the page so badly? I have commented out the print CSS as it contains Font calls but not difference. #Download Invoice as PDF def invoice_download(request, invoice_id): try: #Get the invoice and render it as a string. invoice = BusinessInvoice.objects.get(pk=invoice_id) padcount = [None] * int(8 - invoice.businessinvoiceitem_set.count()) context = {'invoice': invoice, 'padcount': padcount} templatestring = render_to_string('business/invoice_print.html', context, request) #Build the filename the_date = invoice.date.strftime('%Y-%m-%d') filename = "INV%03d-%s-%s.pdf" % (invoice.id, invoice.client, the_date) filename = "".join(filename.split()) fullFilePath = settings.MEDIA_ROOT + 'invoices/' + filename # Turn the HTML into a WeasyPrint HTML object html = HTML(string=templatestring) # Create a list of CSS objects cssList = [ CSS(settings.STATIC_ROOT + 'css/bootstrap.min.css'), #CSS(settings.STATIC_ROOT + 'css/print.css'), ] # Get the PDF as a … -
Django, mod_wsgi and apache2.4 = 403 Forbidden
I facing problem setting up server/django project to WWW As title describe when run server in cmd: C:\Frontier_Website\FATWebsite\Apache24\bin\httpd.exe -k runserver and I open the page get the following; Forbidden You don't have permission to access / on this server. I tried with several stack overflow blog but i don't get any ways to fix my problem: Apache2 mod_wsgi 403 forbidden error Django + mod_wsgi + Apache = 403 Forbidden 403 Forbidden error with Django and mod_wsgi end result: Forbidden You don't have permission to access / on this server. I had also tried vituralenv here my codes: # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" … -
How to create a field based on condition in django that determines if record is duplicate
I need to create new field in the queryset that flags if a record is a duplicate or not. I consider the concatenated values of 2 fields as an identifier. If they are seen more that once in the query set (the field that is concatenated), then the record is considered a duplicate. First, on my query set, I create another field from the existing 2 fields which is case number and hearing date. and their output field name is dupe_id qs = file.objects.annotate( dupe_id=Concat( F('case_no') , F('hearing_date') , output_field=CharField() ) ) then I test this dupe_id field for count. If the count is more than 1, then it is considered as duplicate dupes = qs.values('dupe_id').annotate(dupe_count=Count('dupe_id')).filter(dupe_count__gt=1) at this point I now have another query set the contains the duplicate values from the original query set. Here are the records seen from the dupe object which is of type queryset. It also states the number of instances the value was found <QuerySet [{'dupe_id': 'Test Case No.2018-12-26', 'dupe_count': 3}, {'dupe_id': '123452018-12-26', 'dupe_count': 2}]> Now this is where I'm having a bit of difficulty. What I'm thinking is that I will do an annotation on my main query set and I will use … -
Python sql with 4 table
please help me how to use query in restframework(i dont want to use raw query, if this question no idea i will use raw query instead), I'm new to python and django restframework! my data : tbl product: this is my views.py class Transaction_listlView(viewsets.ViewSet): def list(self, request): user = get_object_or_404(User, pk=request.user.id) queryset = Transaction.objects.filter(user_id = user).exclude(deleted_at__isnull = False) serializer = TransactionSerializer(queryset, context={'fields': ['transaction_id','user_id','address','phone_number','status','total']}, many=True) return Response(serializer.data, status=200) def retrieve(self, request, pk=None): user = get_object_or_404(User, pk=request.user.id) transaction = TransactionVersion.objects.filter(transaction__pk = pk).filter(transaction__user_id = user) serializer = TransactionVersionSerializer(transaction, many=True) return Response(serializer.data) serializers.py class FieldMixin(object): def get_field_names(self, *args, **kwargs): field_names = self.context.get('fields', None) if field_names: return field_names return super(FieldMixin, self).get_field_names(*args, **kwargs) class TransactionSerializer(FieldMixin, serializers.ModelSerializer, object): transaction_id = serializers.IntegerField(source='id') class Meta: model = Transaction fields = '__all__' class TransactionVersionSerializer(serializers.ModelSerializer): product = serializers.IntegerField(source='version_id') class Meta: model = TransactionVersion fields = ('product' , 'quantity') and repsone i want for details transaction(user must login to get transaction): { version_id{ product_name: size: color } quantity this is my data : product table : id, name, des, rate transaction table: id, address ......, user_id transaction_version table: id, quantity, transaction_id, version_id version table: id, size, color ....., product_id -
Why is vim red highlighting closing tags in Django templates?
The image is below. Does anybody know why this is happening? I'm using neovim. Filetype is set to htmldjango. -
dajngo OneToMany relationship using ForeignKey queryset
I use in model in django framework OneToMany relationship using ForeignKey. that I need now and I don't know how to do it is to create a queryset to take for any id in table Order how ids have as fk key in table Line,thst I want to show in html page. for example o want to show in html template something like this: id_order | id_line 1 | 2 2 | 3,4,8 10 | 7 that confused me because I think we need to reverse foreign key here the model : django.db import models class Order(models.Model): order_name = models.CharField(max_length=254) class Line(models.Model): f= models.ForeignKey(Order, blank=True, null=True,verbose_name='order') name = models.CharField(max_length=254) def __unicode__(self): return self.name any idea how to do that ? -
How to redirect the URL without using Protocol(http, https or ftp) in Python?
I am trying to convert PHP code to Python for the payment gateway integration. In PHP, there is a code "header("Location: " . $url);" and the URL is "gatewaysdk://asdzxc?summaryStatus=SUCCESSFUL&3DSecureId=XXXXXX" (without protocol - http, https or ftp). In PHP, the code is working fine. Is there any way to do it in Python. I have tried using redirect and HttpResponseRedirect - return redirect(redirect_url, allow_redirects=True). The error I got was "django.core.exceptions.DisallowedRedirect: Unsafe redirect to URL with protocol 'gatewaysdk'". After debugging the error I found HttpResponseRedirect supports only with protocol (http, https or ftp).