Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'ckeditor_uploader' in django
I'm trying to integrate a ckeditor in my django blog application. I followed all the instructions in the github page of django-ckeditor precisely. i.e. installed, added to installed apps, added in urls, collected staticfiles, configured settings in settings.py and imported ckeditor.fields in models whenever necessary. When I try to make migration or run, I get this error as below: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/kush/projects/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/kush/projects/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/kush/projects/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/kush/projects/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/kush/projects/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/kush/projects/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/kush/projects/venv/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/kush/projects/venv/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/kush/projects/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'ckeditor_uploader' I cant seem to figure out whats wrong here. Anyone here been … -
Django - Haystack Whoosh No Results
I'm using haystack and whoosh for searching. I followed the documentation step by step and already saw these answers: Django-Haystack-Whoosh is giving no results, Django + Haystack + Whoosh, no results in production, django haystack whoosh not showing any errors also no results, no result are found - haystack django whoosh but none could help me. I think it's an problem with my article_text.txt because everything else works. Here's my search index: class ArticleIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr="title") author = indexes.CharField(model_attr="authors") pub_date = indexes.DateTimeField(model_attr="pub_date") def get_model(self): return Article def index_queryset(self, using=None): return self.get_model().objects.visible_for_user() my search_indexes\indexes\article\article_text.txt {{ object.text }} {{ object.title }} {{ object.pub_date }} # This comment isn't in the file but it's an information for you: I also added "neue" to the end of this file to debug but event that didn't work Whenever I say "neue" (I have an article that has "neue" in its title) -
How to refresh part of a Django page with AJAX?
I am deploying a website using Django. There is an application called 'forum', supporting a discussion forum on my website. The url of the discussion forum is 'XXX.com/forum/roomY'. I want to refresh a div id = ''chat'', which includes a message list, on this page when users click a refresh button. I want to use AJAX to do that. But I find that I could not call the function updatestatementlist(request) to retrieve the updated message list so it can be passed to the on this page. /forum/views.py def updatestatementlist(request): log.debug("call statementlist function") statements = Statement.objects.filter(discussion=discussion) return render(request, 'forum/statementlist.html', { 'statements': statements }) I cannot see the log info so I think by clicking the button I fail to call this function. The main html page of the discussion forum is /forum/discussion.html, which is under the template folder. I extract the html code within the div id = "chat" to a separate html /forum/statementlist.html as suggested here and several other SO posts. /forum/discussion.html <button id = "Refresh"> Refresh </button> <div id="chat"> {% include 'forum/statementlist.html' %} </div> /forum/statementlist.html {% recursetree statements %} {% endrecursetree %} forum.js //When users click the refresh button $("#Refresh").on("click", function(event){ alert("Refresh clicked") $.ajax({ url: '', type: "GET", success: … -
Django app not opening from different machine
I have a Django server running on 127.0.0.1:8000 When I try to access it from the same machine then I am able to open my application. But when I try to access this app from a different machine by using machinename:8000 then it says 'This site can't be reached' In my settings.py, I have ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) and ALLOWED_HOSTS= Is this related to above configuration? -
Vue-apexchart is not rendering in async method without any error
I am using vue-apexchart in my application. I am pushing my data from async method in array and looping apexchart in template. I am not getting any error and data is also available in template . When i use codesandbox the functionality get work. Here is the link - https://codesandbox.io/embed/vue-basic-example-1o0xm the same thing i want to achieve in my project but inside the async method where i am getting response from my service and same i am pushing in array which is forwarding in template as well. If anybody knows what's wrong here then please provide the solution. -
saving foreignkey instances in the createview in views.py
I've a models called job, application, attachments. when a job is already created an a user wants to apply for the job I get an integrity error that says null value in column "job_id" violates not-null constraint If I add job in the fields part of class Meta of ApplicationForm everything runs successful but when the user select the job he whats to apply he is forced to select again the job to fill in the job field, So I want is to automatically add the job field to be added in createview in views.py here is my code models.py class Application(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='applied_jobs', null=True, on_delete=models.SET_NULL) job = models.ForeignKey(Job, related_name='applications', on_delete=models.CASCADE) career_briefing = models.CharField(max_length=250, null=True) class Attachments(models.Model): application = models.ForeignKey(Application, related_name='attachments', on_delete=models.CASCADE) cv = models.CharField(max_length=150, null=True) form.py class ApplicationForm(forms.ModelForm): cvs = forms.CharField(max_length=6000, widget=forms.HiddenInput(), required=False) class Meta: model = Application fields = ('career_briefing',) views.py class ApplicationCreateView(LoginRequiredMixin, CreateView): model = Application form_class = ApplicationForm message = _("succesfuly applied") template_name = 'jobs/application_form.html' message = _("successful") def form_valid(self, form): cvs = form.cleaned_data['cvs'] form.instance.user = self.request.user form.instance.job = self.kwargs.get('pk') apply = form.save(commit=False) apply.job = self.kwargs.get('pk') apply.user = self.request.user apply.save() doc = Attachments(cv=cvs) doc.application = apply doc.save() return super(ApplicationCreateView, self).form_valid(form) def get_success_url(self): messages.success(self.request, self.message) … -
Getting error while installing mysqlclient
I AM FACING THIS ERROR WHILE INSTALLING MYSQLCLIENT ON WINDOWS BY PIP ERROR: Command errored out with exit status 1: command: 'c:\users\noob\appdata\local\programs\python\python37\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\NoOB\AppData\Local\Temp\pip-install-fylu3lfn\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\NoOB\AppData\Local\Temp\pip-install-fylu3lfn\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\NoOB\AppData\Local\Temp\pip-record-bknw0h8q\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\NoOB\AppData\Local\Temp\pip-install-fylu3lfn\mysqlclient\ Complete output (24 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\MySQLdb copying MySQLdb__init__.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.7\MySQLdb creating build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\noob\appdata\local\programs\python\python37\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\NoOB\AppData\Local\Temp\pip-install-fylu3lfn\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\NoOB\AppData\Local\Temp\pip-install-fylu3lfn\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\NoOB\AppData\Local\Temp\pip-record-bknw0h8q\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output. -
Credentials aren't allowed error when using Outlook REST API Oauth2 in AWS server
I'm trying to implement Outlook Oauth2 in our Django backend server which is hosted on an AWS instance. I carefully followed the instructions in their python tutorial and it works 100% in my local machine. I am able to grab the authorization code which I then convert in my backend server to an access token. The problem lies in our demo server which is an AWS instance. We have a button that redirects the users to Outlook authentication. The URL has the following format: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=<client-ID-here>&redirect_uri=<demo-server-redirect-url>&response_type=code&scope=openid+profile+offline_access+Calendars.ReadWrite&prompt=consent I am receiving the following error whenever I convert the authorization code into an access token just after the consent screen: { 'error': 'access_denied', 'error_description': 'Your credentials aren't allowed' } The weird thing is that if I use POSTMAN using the demo server Outlook credentials, I am able to retrieve an access token from Outlook. Basically, it works for both in my local machine and using Postman. I really think that I'm just missing a very small piece of code/configuration here. Are there some extra settings that I need to do in order to make Outlook Oauth2 work in AWS? -
how to read Django request.FILES (which is an image) as binary
Sorry for my bad English. I want to get binary image from request which contains image file from ajax. Because when user upload image file, I want to do OCR to the image file using google VISION API. Currently I'm using django, ajax. So when user upload the image, using ajax the file is passed to django view. I tried to get binary file in the views.py. But When I use request.FILES.get('file').read(), there is no data. But request.FILES.get('file').name is 'bank.png'... I think it's weird. Here is some code views.py def receipt_ocr(request): if request.method == 'POST': print(type(request.FILES["file"])) #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'> print(type(request.FILES.get('file'))) #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'> print(request.FILES.get('file')) #bank.png imageFile = request.FILES.get('file') print(imageFile.size) #119227 print(request.FILES.get('file').name) #bank.png print(request.FILES.get('file').content_type) #image/png print(type(request.FILES.get('file').open())) #<class 'NoneType'> print(request.FILES.get('file').open()) #None print(type(request.FILES["file"].read())) #<class 'bytes'> for chunk in imageFile.chunks(): print(chunk) #this generates lot of binary and some rdf:Description rdf:about= ... things receipt_image = imageFile.read() print(type(receipt_image)) print(receipt_image) ajax part // receipt OCR process $.ajax({ url: "{% url 'place:receipt_ocr' %}", enctype: 'multipart/form-data', type: 'POST', processData: false, contentType: false, data: postData, complete: function(req){ alert('good'); }, error: function(req, err){ alert('message:' + err); } }); What I exactly want to do is using this kind of code (google VISION API example code, OCR) def detect_text(path): """Detects text in the file.""" … -
models with ManyToManyField
suppose that you want to simulate universities system, you have courses, teachers, students. we have some courses that present by some teachers and student choose some courses with some teachers. for example: courses: math, physics teachers: Jack(math), Jane(math, physics) students: st1(math with Jack), st2(math with Jane), st3(physics with Jane and cant choose Jack!!), every score by default=-1. with this code: teachers = models.ManyToManyField(teacher.objects.filter(t_courses=s_courses), verbose_name='Ostad') I got errors like: raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet from django.db import models class profile(models.Model): n_id = models.IntegerField(primary_key=True, verbose_name='code melli') name = models.CharField(max_length=24, verbose_name='Full Name') class Meta: ordering = ('name',) class course(models.Model): name = models.CharField(max_length=24, verbose_name='Class Name') unit = models.SmallIntegerField() class Meta: ordering = ('name',) def __str__(self): return self.name class teacher(profile,models.Model): t_id = models.AutoField(primary_key=True) t_courses = models.ManyToManyField(course, verbose_name='Dars') def __str__(self): return self.name class student(profile,models.Model): s_id = models.AutoField(primary_key=True) s_courses = models.ManyToManyField(course, verbose_name='Dars') #teachers = ?????????????????????????? score = models.IntegerField(default=-1, verbose_name='Nomre') def __str__(self): return self.name I don't know about coding in the teachers part. Thanks alot -
How to run django test on google cloud platform
i'm deploying my app on Google Cloud platform. Every thing seems to be set up correctly but when i try to launch test, i get this error : ====================================================================== ERROR: purbeurre.core (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: purbeurre.core Traceback (most recent call last): File "/usr/lib/python3.6/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/usr/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'purbeurre.core' Is there a special setting to have all my test modules loaded ? i did check locally and it's working on my dev environnement -
How to differentiate b/w receiver and sender in django?
I have a problem when sending an email. Whenever I send an email from bilalkhangood6@gmail.com to bilalkhangood4@gmail.com. The email I open shows me that bilalkhangood4@gmail.com is the receiver and sender also. The email shows me that it is sent and received both from bilalkhangood4@gmail.com Although this is not the case. The send sender is bilalkhangood6@gmail.com and receiver is bilalkhangood4@gmail.com settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'bilalkhangood4@gmail.com' # this should an official account from which every user will get password change link EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 ACCOUNT_EMAIL_VERIFICATION = 'none' views.py class ViewSendEmail(FormView): form_class = FormEmailSend template_name = 'nextone/email_send.html' def form_valid(self, form): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] from_email = form.cleaned_data['from_email'] to_email = form.cleaned_data['to_email'] emails = [] if ',' in to_email: for email in to_email.split(''): emails.append(email) else: emails.append(to_email) if 'send_mail' in self.request.POST: send_mail_example(subject, message, from_email, emails) else: send_email_message(subject, message, from_email, emails) return redirect('ViewSendEmail') def send_email_message(subject, message, from_email, emails): email = EmailMessage(subject, message, from_email, to=emails) email.send() def send_mail_example(subject, message, from_email, emails): send_mail(subject, message, from_email, emails) forms.py class FormEmailSend(forms.Form): to_email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Email(s) to send to','class': 'form-control'})) subject = forms.CharField(required=False,widget=forms.TextInput(attrs={'placeholder': 'Subject', 'class': 'form-control'})) message = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Email body', 'class': 'form-control'})) from_email = forms.EmailField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Email(s) from receive … -
Why is the return value of a model method in Django not showing up to the template?
I have this function inside my model that is not appearing when I try to run the server. I think I am accessing the method correctly but when I tried writing print("ENTER") inside the total_balance() function, nothing showed up which makes me think that it's not even entering the method at all. Oddly, the function works if I take out the search functionality. model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def total_balance(): transaction_list = Transaction.objects.filter(user=User) total_balance_amount = 0 for transaction in transaction_list: if transaction.category=='Income': total_balance_amount += transaction.amount elif transaction.category=='Expense': total_balance_amount -= transaction.amount return total_balance_amount views.py def profile(request): if request.method == 'GET': query = request.GET.get('q') if query and query!="": results = Transaction.objects.filter(Q(tag__icontains=query)) else: results = Transaction.objects.all() transactions = { 'transactions' : results, } profile = { 'profile' : Profile.objects.all() } return render(request, 'users/profile.html', transactions, profile) template.py <h5 class="card-title">Total Balance</h5> <p class="card-text">₱{{ profile.total_balance }}</p> Can someone please help me identify the reason this is not working and how I might be able to fix it? Thank you. -
Django inline formset with manytomany fields
Ive spent a fair bit of time searching on this subject without finding some real up to date answers. I'm trying to create a form that creates a db entry. The basic idea is this: Many events can have many people So, the struggle here is that the user needs to create an event where the user can select all the people that attend. Each person that attends though, has certain things that also needs to be tracked per event. See the model below: models.py from django.db import models from django.contrib.auth.models import User[] class PersonRole(models.Model): role = models.CharField(max_length=20, choices=ROLE_CHOICES, unique=True) # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.role class PersonClass(models.Model): name = models.CharField(max_length=100, choices=CLASS_CHOICES, unique=True) color = models.CharField(max_length=6, choices=COLOR_CHOICES, unique=True) # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.name class Person(models.Model): name = models.CharField(max_length=100, unique=True) personclass = models.ForeignKey(PersonClass, on_delete=models.CASCADE, blank=True, null=True) personrole = models.ForeignKey(PersonRole, on_delete=models.CASCADE, blank=True, null=True) value = models.IntegerField(default=0) reliability = models.IntegerField(default=0) last_item = models.DateField(auto_now=False, blank=True, null=True) last_event_attended = models.DateField(auto_now=False, blank=True, null=True) last_manager_attended = models.DateField(auto_now=False, blank=True, null=True) item_received = models.BooleanField(default=False) … -
Data relationship on application level in Django
Is it possible to build data relationship on programming level using models but not in tables, If yes how. For example in Laravel we can define model relationship inside model, it does not require database level foreign key relations. My question is, Like that can we define that in Django model or any other methods to achieve that. -
multiprocessing in python with error 'takes 1 positional argument but 2 were given'
) i'm a beginner in python and django and try to run a external code with multiprocessing. On my first try import a .txt with numpy, my code runs. On my second try to import a .csv with pandas, i get an error message. What is the different? Why doesn't run the second try? quick.py import os import pandas as pd import numpy as np def import_txt(q, w_url): w_data = np.loadtxt(w_url,delimiter=';', dtype='str') q.put(w_data) def import_csv(q, w_url): w_data = pd.read_csv(w_url) w_data.head() q.put(True) views.py from multiprocessing import Process, Queue, set_start_method from app.static.code.quick import import_txt as q_txt from app.static.code.quick import import_csv as q_csv this works def q_history(request): if request.method == 'POST' and request.is_ajax(): #erstellt den pfad m_user = request.user.username m_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) m_dir = os.path.join(m_dir, 'app', 'media', m_user, 'quick', 'ini.txt') set_start_method('spawn', True) q = Queue() p = Process(target=q_txt, args=(q,m_dir)) p.start() m_data = q.get() p.join() return JsonResponse(m_data.tolist(), safe=False) else : assert isinstance(request, HttpRequest) return render( request, 'quick.html', { 'title':'title', 'message':'Your application description page.', 'year':datetime.now().year, } ) this not def q_csv(request): if request.method == 'POST' and request.is_ajax(): #erstellt den pfad m_user = request.user.username m_file = '2019_Test.csv' m_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) m_dir = os.path.join(m_dir, 'app', 'media', m_user, 'quick', 'input', m_file) set_start_method('spawn', True) q = Queue() p = … -
Get images from database as known images for Facial recognition
I am playing around with a time attendance application that is going to utilize facial recognition. When you create a user, you add three pictures of that user and those pictures are saved in the database. Note that I'm using Django and Django models for this. I am thinking of connecting to the database itself because I can't of an easier way of retrieving the images from Django Models outside of Django. Anyways. Consider a standard OpenCV Facial recognition code. It has a thing called known images. What I want to do, is when a user enters their ID, the program retrieves the images of that user. The thing I don't understand, is how do I directly use those images for known_images. Do I first save the images in the OS's temp folder and read from there? Or how do I do this? Thank you, any and all ideas are appreciated. -
Adding a profile image in django is not working
I am trying to add profile image to my page, but for some reason "my image" text is shown instead of a image. I do not have any clue about what is wrong in my code, i jave read trough multiple tutorials and they all tells me to do this way. I have a folder "media" in my root directory and inside that i have folder "profile_pics". I have added these to settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' these to urls.py from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is my html {% load static %} {%block content%} <div class="content-section"> <div class="media"> <img src="{% static "profile_pics/default.jpg" %}" alt="My image"/> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> </div> {%endblock content%} models.py class profiili(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) kuva=models.ImageField(default='default.jpg', upload_to='profile_pics') -
Sending data from form python
When I click on search button I need to get data using google api, but I get this error page. https://i.stack.imgur.com/imj6T.png index.html <!DOCTYPE html> <html> <head> </head> <body> <form method="POST"> {% csrf_token %} <input type="text" name="search" placeholder="some text"><br> <button class="button" name="submit" type="submit">Search</button> </form> </body> </html> views.py from django.http import HttpResponse from django.shortcuts import render def index(request): if request.method == 'GET': return render(request, 'index.html', context={}) # Handles the search once the submit button in the form is pressed # which sends a "POST" request if request.method == 'POST': # Get the input data from the POST request search_query = request.POST.get('search', None) # Validate input data if search_query and search_query != "": try: from googlesearch import search except ImportError: print("No module named 'google' found") for j in search(search_query, tld="co.in", num=10, stop=1, pause=2): print(j) else: return HttpResponse('Invalid input.') urls.py from django.urls import path from firstapp import views urlpatterns = [ path('', views.index, name='home') ] Please, help to solve that. -
Is there any specific way to override search_indexes of oscar core search app?
I am using Haystack with solr back-end in Django-Oscar. I want to override ProductIndex class of core search_indexes. But, the problem is it's not working with the regular way. Firstly, I forked the search app like other oscar apps. And I created custom ProductIndex class inside search_indexes.py file. I also tried excluding core search_indexes in setting. But, it's not taking from the overridden app. My custom class looks like: """ from oscar.apps.search.search_indexes import ProductIndex as AbstractProductIndex class ProductIndex(AbstractProductIndex): def index_queryset(self, using=None): # Only index browsable products (not each individual child product) return self.get_model().objects.all().order_by('-date_updated') def read_queryset(self, using=None): return self.get_model().objects.all().base_queryset() """ The ProductIndex class is supposed to run from my overridden app but, instead it's using core ProductIndex app. -
How to satisfy unique constraint in django unit test without hardcoding?
I have set a unique constraint on email field of my Member model. Now while writing unit tests, my tests fail due to expiring unique constraint. def setUp(self): self.car_provider = mommy.make(Member, username="car_provider") self.car_provider.set_password("12345678") self.car_provider.save() self.applicant = mommy.make(Member, username="applicant") self.applicant.set_password("12345678") self.applicant.save() I get following error: "django.db.utils.IntegrityError: duplicate key value violates unique constraint "account_member_email_a727987b_uniq" DETAIL: Key (email)=() already exists." -
Django zip multiple files from the list
Trying to compress multiple files and download .zip file via button. Here is my code: VIEW.py files = ['file1.txt','file2.txt','file3.txt'] file_path = os.path.join(settings.MEDIA_ROOT, '/') def downloads_files (requests): if 'zipall' in request.POST: if len(config_filenames) > 0: zipfile_name = zipped(directory=file_path, file_list=files ) resp = HttpResponse(FileWrapper(open(zipfile_name,'rb')), content_type='application/zip') resp['Content-Disposition']='attachment;filename=%s' % zipfile_name return resp def zipped(directory, file_list): zip_filename=directory + strftime("zipped_%Y_%m_%d_%H%M%S", gmtime()) + '.zip' with ZipFile(zip_filename, 'w') as zip1: for current_file in file_list: # Add file to zip zip1.write(directory+current_file) return zip_filename I was able to download, but when I unzip, creates a lengthy name and also create subfolder based on the root. Long name: _Users_<user>_<projectfolder>_src_media_zipped_2019_08_18_081747.zip -
How to Implement Dependent Dropdown list in Django
I have a Food table which contains Food name and it's price.Whenever a user selects a food from template form,the price associated with it should automatically be displayed in the form. How can I do it ?? models.py class Food(model.Models): name = models.CharField(max_length = 100) price = models.IntegerField() class Payment(models.Model): food = models.ForeignKey(Food, on_delete=models.CASCADE) forms.py class PaymentForm(forms.ModelForm): class Meta: model = Payment fields = '__all__' views.py def payment_details(request): amounts = Food.objects.all() context={ 'amounts' : amounts } return render(request, 'app_name/payment.html',context) template <label>Select the Food</label> <select name="name" class="form-control" required> {% for amount in amounts %} <option value="{{amount.food.name}}">{{amount.food.name}}</option> {% endfor %} </select> <label>Amount You Need to Pay</label> <select name="name" class="form-control" required> {% for amount in amounts %} <option value="{{amount.food.price}}">{{amount.food.price}}</option> {% endfor %} </select> -
Map raw sql query with join to model in Django
I want to execute a raw SQL query and map the result to model. Let's say I have the following model: class Message(Model): id = AutoField(primary_key=True) user = ForeignKey(User) test = CharField(max_length=100) And let's assume this is the raw SQL query I am trying to execute: messages = Message.objects.raw('SELECT * FROM message m JOIN user u ON m.user_id = u.id') However, I am having a hard time understanding how to map user fields from db to user fields in my Message model. The reason why I am using raw SQL query is that the original query seems to be quite complex to do it using Django ORM. It seems to be an easy task but I couldn't find an answer online. -
which front end framework best suits django?
which front end framework best suits django?