Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django display table in templates
I am using Django 2.0.1, and I have the following code: Models.py: class Category(models.Model): category_name = models.CharField(max_length=50) class CategoryItems(models.Model): category_name = = models.ForeignKey(Categories, related_name='categoriesfk', on_delete=models.PROTECT) item_name = models.CharField(max_length=50) item_description = models.CharField(max_length=100) Thereafter my views.py: def data(request): categories_query = Categories.objects.all() category_items_query = CategoriesItems.objects.all() return render_to_response("data.html", {'categories_query': categories_query,'category_items_query': category_items_query} In the template I'm trying to display all items for each category, for example, suppose there are 4 categorizes, e.g. Bicycle, then it display all items belonging to that category only. For example, as follows: Category 1: Category_Item 1, Category_Item 2, Category_Item 3, and so on ... Category 2: Category_Item 1, Category_Item 2, Category_Item 3, and so on ... I have tried to write so many different for-loops, but they just display all items, I need it to show items only for that category, then for loop to next category and show items for that. Please may I kindly ask for some help? -
How to use a field of subquery in Django for joins?
SELECT CSR1.ConsumerProductID, CSRF1.Rating, CSRF1.CreatedDate FROM (SELECT CP.ConsumerProductID, COUNT(CSRF.Rating) FROM consumer_servicerequest_feedback CSRF INNER JOIN consumer_servicerequest CSR ON CSRF.ConsumerServiceRequestID=CSR.ConsumerServiceRequestID INNER JOIN consumer_product CP ON CP.ConsumerProductID=CSR.ConsumerProductID WHERE CSRF.Rating IS NOT NULL AND CSRF.CreatedDate GROUP BY(CSR.ConsumerProductID) HAVING(COUNT(CP.ConsumerProductID)>1)) AS T INNER JOIN consumer_servicerequest CSR1 ON T.ConsumerProductID=CSR1.ConsumerProductID INNER JOIN consumer_servicerequest_feedback CSRF1 ON CSRF1.ConsumerServiceRequestID=CSR1.ConsumerServiceRequestID ORDER BY T.ConsumerProductID, CSRF1.CreatedDate; I have to perform a query something like above in Django. innerq = ConsumerServicerequestFeedback.objects.values_list('csrfconsumerservicerequestid__csrconsumerproductid').exclude( csrfcreateddate__isnull=True).exclude(csrfrating__isnull=True).order_by( 'csrfconsumerservicerequestid__csrconsumerproductid').annotate( count_status=Count('csrfconsumerservicerequestid__csrconsumerproductid')).filter( count_status__gt=1) res_list = [x[0] for x in innerq.values_list('csrfconsumerservicerequestid__csrconsumerproductid')] q = ConsumerServicerequestFeedback.objects.values_list('csrfconsumerservicerequestid__csrconsumerproductid', 'csrfrating', 'csrfcreateddate').filter(status).filter( csrfconsumerservicerequestid__csrconsumerproductid__in=(res_list)).exclude(csrfcreateddate__isnull=True).exclude( csrfrating__isnull=True) I am doing something like this. Now I need to use the consumerproductID of the new table(innerq) as I did in SQL in my q query(wanted to use as join), How can I do that? -
Django : Unable to run server
I am new to Django and this is the first project Im working on. I have an error while executing the runserver command. Im working with Python 3.6.4. I havent found a solution in previous posts which were already very few. This is the error I get : Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x0000022D586C2C80> Traceback (most recent call last): File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\site- packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\site- packages\django\core\management\commands\runserver.py", line 151, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\site- packages\django\core\servers\basehttp.py", line 164, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\site- packages\django\core\servers\basehttp.py", line 74, in __init__ super(WSGIServer, self).__init__(*args, **kwargs) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\socketserver.py", line 453, in __init__ self.server_bind() File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\http\server.py", line 138, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe8 in position 2: invalid continuation byte PS : Please dont ask me to uninstall all and reinstall because I did it several times in vain. -
My django app on heroku is running but logs says it is crashed
I have a django app running on heroku. It is online, and I can access it and it is working on http://demo.dagenssalg.dk But I can't submit changes to it, and in the log it says it is chrashed. Feb 02 07:17:17 dagenssalg app/web.1: ImportError: bad magic number in 'form.admin': b'\x03\xf3\r\n' Feb 02 07:17:17 dagenssalg app/web.1: [2018-02-02 15:17:17 +0000] [9] [INFO] Worker exiting (pid: 9) Feb 02 07:17:17 dagenssalg app/web.1: [2018-02-02 15:17:17 +0000] [8] [INFO] Worker exiting (pid: 8) Feb 02 07:17:17 dagenssalg app/web.1: [2018-02-02 15:17:17 +0000] [4] [INFO] Shutting down: Master Feb 02 07:17:17 dagenssalg app/web.1: [2018-02-02 15:17:17 +0000] [4] [INFO] Reason: Worker failed to boot. Feb 02 07:17:17 dagenssalg heroku/web.1: Process exited with status 3 Feb 02 07:17:18 dagenssalg heroku/web.1: State changed from up to crashed What am I missing? Any help is most appreciated. Best regards Kresten -
Django : changing a specific form in modelformset
Here is the riddle. This is a simplified version of the problem I am dealing with, just so we can capture the core problem. So, for the sake of simplicity and relevance, not all fields and relationships are shown here. So, I have a modelformset and I would like to access each individual form to change the field based on the queryset. class PlayerType(models.Model): type = models.CharField(max_length=30, choices = PLAYER_TYPES) class Player(models.Model): name = models.CharField(max_length=30, blank=False, null=False) player_type = models.ForeignKey(PlayerType, related_name ='players') contract_price = models.DecimalField(max_digits = 10, decimal_places = 2, blank = False, null = False) price_unit_of_measurement = models.CharField(max_length=20, choices=STANDARD_UOM) Forms.py class PlayerForm(ModelForm): class Meta: fields = ['name','price_unit_of_measurement'] views.py PlayerFormSet = modelformset_factory(Player, form = PlayerForm, extra = 5) Now, say I want to display a different unit of measurement depending on which player I am showing. For instance, player 1's contract may be based on lump sump or amount per game, and another player's contract may be based on number of minutes played, price per month, etc. depending on the player type. In essence, I would like to know how to access each form in a modelformset and change the unit of measurement for that form alone, from the default … -
Django model filefield clear checkbox function is not working with using clean method of field
Clear checkbox for filefield like (image) is not working when i am using the clean function for the field clean function: def clean_image(self): #file = self.cleaned_data['image'] file = self.cleaned_data['image'] if file: if not os.path.splitext(file.name)[1] in [".jpg", ".png"]: raise forms.ValidationError( _("Doesn't have proper extension")) return file But if i remove the clean function the checkbox clear functionality is working fine, is there any conflict in using these two methods -
NOT NULL constraint failed: courses_course.owner_id
I'm creating a school, kinda, and I get NOT NULL constraint failed: courses_course.owner_id whenever I try to create a course via the URL http://127.0.0.1:8000/course/create/. Here are my files: models.py from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from .fields import OrderField class Subject(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ('title',) def __str__(self): return self.title class Course(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='courses_created') subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='courses') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) def __str__(self): return self.title class Module(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='modules') title = models.CharField(max_length=200) description = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['course']) class Meta: ordering = ['order'] def __str__(self): return '{}. {}'.format(self.order, self.title) class Content(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE, related_name='contents') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to={ 'model__in':('text', 'video', 'image', 'file') }) object_id = models.PositiveIntegerField() item = GenericForeignKey('content_type', 'object_id') order = OrderField(blank=True, for_fields=['module']) class Meta: ordering = ['order'] class ItemBase(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_related') title = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True def __str__(self): return self.title class Text(ItemBase): content = models.TextField() class File(ItemBase): file = models.FileField(upload_to='files') class Image(ItemBase): file … -
Always image cannot be sent normally
Always image cannot be sent normally. I wrote in views.py def photo(request): d = { 'photos': Post.objects.all(), } return render(request, 'registration/accounts/profile.html', d) def upload_save(request): form = UserImageForm(request.POST, request.FILES) if request.method == "POST" and form.is_valid(): data = form.save(commit=False) data.user = request.user data.save() return render(request, 'registration/photo.html') else: return render(request, 'registration/profile.html') in profile.html <main> <div> <img class="absolute-fill"> <div class="container" id="photoform"> <form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data" role="form"> {% csrf_token %} <div class="input-group"> <label> <input id="file1" type="file" name="image1" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label> <input id="file2" type="file" name="image2" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label> <input id="file3" type="file" name="image3" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <input id="send" type="submit" value="SEND" class="form-control"> </form> </div> </div> </div> </main> In my system,I can send 3 images at most each one time, so there are 3 blocks.Now always program goes into else statement in upload_save method, I really cannot understand why always form.is_valid() is valid.When I send only 1 image, same thing happens.So the number of image does not cause the error.How should I fix ?What is wrong in my code? -
Django get_or_create race condition when creating related objects
I have an ExtendedUser model like this, that just points to Django's User model: class ExtendedUser(models.Model): user = models.OneToOneField(User) When a request comes in, I want to get or create an User and its related ExtendedUser if the user that I'm looking for doesn't exist. I have this code : def get_or_create_user(username): with transaction.atomic(): user, created = User.objects.get_or_create( username=username, defaults={ 'first_name': "BLABLA", }, ) if created: extended_user = ExtendedUser() extended_user.user = user extended_user.save() return user I wrap it inside a transaction, to be sure I don't create an User but not its associated ExtendedUser. But, when two requests come in simultaneously that will create the same user, this fails from time to time with an IntegrityError, for both requests. So I end up with no user being created.. IntegrityError: (1062, "Duplicate entry 'BLABLABLA' for key 'username'") Note that I use MySQL, but I force READ COMMITTED isolation level. What do I do wrong ? How should I handle this ? The models need to stay as they are. -
Django 2.0 FormView for searching
I am using Django for few weeks, so I am still bit new in this. I want a page where I will have searching form and table with results. So each time I click search it will stay on same page and results will changed. I did read a lot of threads here about that, but some of them are old. So I did get quite confuse because find a lot of ways how to do that. I did find some solution but want to be sure that is it in "django" way. first target is to have page with searching for only. So after click search I will get search text under form, which will keep text. urls.py: from django.urls import path from . import views app_name = 'pocitadla' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('pokus', views.Pokus.as_view(), name='pokus'), ] forms.py: class PokusForm(forms.Form): name = forms.CharField(label='text to search', initial='what you want') processing with GET template: pocitadla/pokus.html {% extends "hlavna/header.html" %} {% block content %} <h2>testing</h2> <div> <form action="" method="get"> {{ form.as_p }} <button class="btn btn-success" type="submit">search</button> </form> </div> <h3>you did search for this</h3> <p>{{ pokus_pokus }}</p> {% endblock %} VIEW: class Pokus(FormView): template_name = 'pocitadla/pokus.html' search = None def get(self, … -
Django: get all objects among the foreignkey and inheritance related models?
Belows are my model design: class Exchange(BaseModel): name = models.CharField(max_length=20) class Symbol(BaseModel): exchange = models.ForeignKey(Exchange) name = models.CharField(max_length=20) class ASymbol(Symbol): a_property = models.CharField(max_length=20) class BSymbol(Symbol): b_property = models.CharField(max_length=20) my_exchange = Exchange.objects.first() How can I get all BSymbol objects using my_exchange variable and related manager? Something like my_exchange.symbol_set.filter(~~~)? Notice : Symbol is not an abstract class. Thanks -
Django cms content getting published in draft mode
I have installed djangocms-snippet and using placeholder in my template as shown in image I have included placeholder on template page like {% block content %} {% placeholder "Articles" %} {% endblock content %} Issue: whenever I am updating snippet for e.g. news and changing content and then saving its getting reflected automatically in live version without having clicked "publish page changes".Ideally it should only be reflected to the logged in user and after verifying changes are correct I can publish but as soon as i am changing content and saving its getting reflected on live page.Live refers to staging environment here. -
Reverse not found
I'm using Django 1.7 and I have this URL pattern: url(r'^account/unsubscribe/(?P<user_id>[^/.]+)/(?P<token>[\w.:\-_=]+)$', views.unsubscribe, name='account-unsubscribe') And I have this in my project code: def create_unsubscribe_link(self): email, token = self.user.email_notifications.make_token().split(":", 1) user_id = TelespineUser.objects.get(email=email) return reverse('account-unsubscribe', kwargs={'user_id': user_id, 'token': token, }) Why do I get this while calling create_unsubscribe_link?: NoReverseMatch: Reverse for 'account-unsubscribe' with arguments '()' and keyword arguments '{'token': '1ehbA0:czK8xR8IGiGu7WdEuYRkYigXBzI', 'user_id': <TelespineUser: name: demo@telespine.com, id: 1>}' not found. 1 pattern(s) tried: ['api/v1/account/unsubscribe/(?P<user_id>[^/.]+)/(?P<token>[\\w.:\\-_=]+)$'] -
Can you tell me how to Start django project in pydroid2?
I am using pydroid 2 in my android to learn python and couldnot figure how start a django project. I have already installed django -
SocialApp matching query does not exist
I m getting this error as soon as I m clicking on sign up href link. I m unable to figure out what's the problem if someone can help me out I would really appreciate that : Error DoesNotExist at /accounts/github/login/ SocialApp matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/github/login/ Django Version: 1.8.7 Exception Type: DoesNotExist Exception Value: SocialApp matching query does not exist. Exception Location: /usr/lib/python2.7/dist-packages/django/db/models/query.py in get, line 334 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/vaibhav/Desktop/projects/food_orders', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/vaibhav/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0'] Server time: Fri, 2 Feb 2018 18:41:48 +0000 My settings.py looks like this : # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'restaurants', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.github', ) SITE_ID = 2 # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) LOGIN_REDIRECT_URL = 'home' ACCOUNT_EMAIL_VERIFICATION = 'none' My views.py … -
How to display contact form on landing page in Django
I have a little answer. Like in the subject. I have a landing page and all of hrefs to another pages looks like this <article id="kontakt"> and the link from menu looks like this <li><a href="#kontakt">Kontakt</a></li> I've created a newapp names kontakt witch include: forms.py from django import forms class WyslijEmail(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(required=True,widget=forms.Textarea) views.py from django.shortcuts import render, redirect from django.core.mail import send_mail from .forms import WyslijEmail def kontakt(request): sent = False if request.method == 'POST': form = WyslijEmail(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] send_mail(subject, message, from_email,['my@mail.com']) sent = True else: form = WyslijEmail() return render(request,'strona/index.html', {'form':form, 'sent': sent}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.kontakt, name='kontakt'), ] And on the end I have a html code : <article id="kontakt"> <h2 class="major">Kontakt</h2> {% if sent %} <h4>Wiadomość została wysłana</h4> {% else %} <form action="." method="post" name="kontakt"> {% csrf_token %} {{ form.as_p }} <p><input type="submit" value="Wyślij wiadomość"></p> </form> {% endif %} The result is that, when I runserver and clik on the mainpage in link 'Kontakt', the javascript opened me a window with kontakt but displaying me only a table with … -
Python unit test : Why need `mock` in a test?
I can not understand why we need mock in some test cases, especially like below: main.py import requests class Blog: def __init__(self, name): self.name = name def posts(self): response = requests.get("https://jsonplaceholder.typicode.com/posts") return response.json() def __repr__(self): return '<Blog: {}>'.format(self.name) test.py import main from unittest import TestCase from unittest.mock import patch class TestBlog(TestCase): @patch('main.Blog') def test_blog_posts(self, MockBlog): blog = MockBlog() blog.posts.return_value = [ { 'userId': 1, 'id': 1, 'title': 'Test Title, 'body': 'Far out in the uncharted backwaters of the unfashionable end of the western spiral arm of the Galaxy\ lies a small unregarded yellow sun.' } ] response = blog.posts() self.assertIsNotNone(response) self.assertIsInstance(response[0], dict) This code is from this blog. What I'm curious about is that as you can see in test code, test code set blog.posts.return_value as some desirable object(dict). But, I think this kind of mocking is useless because this code just test How well the user set the return_value correctly in the test code, not what the real Blog' object really return. What I mean is, even if I make real posts function return 1 or a in main.py, this test code would pass all the tests because the user set the return_value correctly in the test code! Can … -
How to serve a view at every URL endpoint
The reason for my wanting to serve the same view at every URL endpoint, is because the view sends Notification information to the authenticated user. For example, here is the view which has data that I would like served in every page: class NotificationsView(View): def get(self, request, *args, **kwargs): profile = Profile.objects.get(user__username=self.request.user) notifs = profile.user.notifications.unread() return render(request, 'base.html', {'notifs': notifs}) I'm trying to send the context variables into my template to be used with javascript. The JS file lives apart from the template, so I'm attempting to declare the global JS vars in the base template first, then use them in the JS file. base.html: ... {% include "landing/notifications.html" %} <script src="{% static 'js/notify.js' %}" type="text/javascript"></script> {% register_notify_callbacks callbacks='fill_notification_list, fill_notification_badge' %} landing/notifications.html: <script type="text/javascript"> var myuser = '{{request.user}}'; var notifications = '{{notifs}}'; </script> notify.js: ... return '<li><a href="/">' + myuser + notifications + '</a></li>'; }).join('') } } Based on this code, you can see how I've ended up in a predicament where I need to use the CBV to send the proper notifications to the landing/notifications.html in order to make sure the javascript variables can be dynamically rendered for the JS file. I am utterly confused as to how the … -
How can I change the checkbox button in django admin to toggle switch button?
I am trying to customize the django admin section and want to change the checkbox of a model attribute (BooleanField) into a toggle switch. -
Django httpresponse returns corrupted file
I'm trying to deploy a Django application i just got handover from an ex-colleague to a server on my network, the application runs perfectly on my laptop with python manage.py runserver I took the application and set up the environment on the server and ran the app there it works fine but there is this part where i return a XLSM file format to the user using HTTPresponse but it returns a corrupted file, the code already saves a copy of the file to be returned in the app folder and this file is fine and not corrupted, also when i compared the two files i found the correct file size is 93 KB but the corrupted returned file is 269 B. The part of the code which returns to the user the file is as follows excel_file = BytesIO() writer = pd.ExcelWriter(excel_file, engine='xlsxwriter') #result_final is the file i save on the hard disk result_final.to_excel(writer, sheet_name='Summary Report') workbook = writer.book my_worksheets = {} for worksheet in workbook.worksheets(): my_worksheets[worksheet.get_name()] = worksheet worksheet = my_worksheets['Summary Report'] workbook.add_vba_project('./vbaProject.bin') worksheet.insert_button('E3', {'macro': 'Macro5', 'caption': 'Load Charts', 'width': 70, 'height': 70}) writer.save() workbook.close() excel_file.seek(0) response = HttpResponse(excel_file.read(), content_type='application/vnd.ms-excel.sheet.macroEnabled.12') response['Content-Disposition'] = 'attachment; filename=Summary Report.xlsm' return response This … -
when to use "/" (project/app/model) and when to use dotted path (project.apps.models) in django
Can someone explain the logic and reason when to use the dotted path and when to use the path with slash("/") in django ? When we write path in terminal it is python manage.py test project.apps.tests but when it is written in code (templates etc) its like projects/apps/directory. I didnt find any related question. If this question is already asked please provide the link. -
Django: text search: Haystack vs postgres full text search
I am using Django 2.0 I have posts with title and description. For the first time i am trying to implement search functionality. I found after searching the following options: Haystack and postgres full text search (https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/search/) Which is the suggested one to work with. -
django: full text search for sqlite database
I am using Django 2.0. I have a list of posts with a title and descrption. I have found the full text search documentation for postgres database at https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/search/. I am presently using sqlite database. I there any documentation for sqlite database full text search in Django. -
In Django test there is empty queryset when assigned to variable but not empty when printed in console during debug
I'm debugging Django (1.11.8) test and observing strange behavior: when stopped in debugger and switched to Ipython console typing: Model.objects.all() returns non-empty Queryset. However, when the same expressions is assigned to variable e.g.: obj_qs = Model.objects.all() then obj_qs is empty Queryset. I would expect the same result from both statements. Am I missing something important in tests setup? I'm using both setUpTest() and setUp() methods to initialize objects for the test. -
Send Json string from javascript in chrome extension to django
I am working on a chrome extension where I have a simple form when we click on a extension icon. This form data has been converted into JSON string. This was fine and working correctly.I want to send this JSON string from java script which is in chrome extension to Django and thereby I have to store Json data in Mysql database. popup.js: document.addEventListener('DOMContentLoaded', documentEvents, false); function myAction(fname,femail,fpassword) { var json={ "email":fname.value, "name":femail.value, "password":fpassword.value }; var html = JSON.stringify(json); alert(html); /*var json_obj = document.getElementById('output'); json_obj.value=html;*/ var xmlhttp = new XMLHttpRequest(); var theUrl = "http://127.0.0.1:8000/music/"; xmlhttp.open("POST", theUrl, true); xmlhttp.onreadystatechange = function() { alert(xmlhttp.readyState + " " + xmlhttp.status); if (xmlhttp.readyState == 4){ alert("entered"); } else{ alert("not entered"); } }; xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xmlhttp.send(html); } function documentEvents() { var submitButton = document.getElementById('submit') submitButton.addEventListener('click', function(event) { var formId = document.getElementById('test'); var name = document.getElementById('name'); var email = document.getElementById('email'); var password = document.getElementById('password'); myAction(name,email,password); }); } popup.html <!DOCTYPE html> <html> <head> <title>Wonderful Extension</title> <script src="popup.js"></script> </head> <body> <div style="padding: 20px 20px 20px 20px;"> <h3>Hello,</h3> <p>Please enter your name : </p> <form id="test" action="#" method="post"> <div class="form-group"> <label for="email">Email</label> <input class="form-control" type="text" name="Email" id="email" /> </div> <div class="form-group"> <label for="name">Name</label> <input class="form-control" type="text" name="Name" id="name" /> </div> …