Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Within a view, how do I return the MEDIA_URL for Imagefield queryset?
Assume I have the following model: class ProductImage(models.Model): image = models.ImageField('Product image', null=True,blank=True) view = models.CharField(max_length=2, choices=VIEW_TYPES, default='FR', null=True,blank=True) description = models.CharField(max_length=125, blank=True, null=True) def __str__(self): return self.view + "-" + self.image.url I have the following queryset: allProductImages = ProductImage.objects.all() How do I extract the MEDIA_URL + path + filename for all objects (e.g. /media/image.jpg) here's what I have already tried (follows on from previous queryset statement): urlValues = allImages.values('image') <QuerySet [{'image': 'greenSwatch.jpg'}, {'image': 'blueSwatch.jpg'}, {'image': '3037-outer-black.jpg'}, {'image': '3037-outer-black.png'}] I'm trying to get the following: <QuerySet [{'image': '/media/path/greenSwatch.jpg'}, {'image': '/media/path/blueSwatch.jpg'}, {'image': '/media/path/3037-outer-black.jpg'}, {'image': '/media/path/3037-outer-black.png'}, {'image': '/media/path/3037-inner-blue.png'}, {'image': '/media/path/3037-outer-green.png'}, {'image': '/media/path/3037-outer-blue.png'}]> Also, I know there's no upload_to parameter specified, but this is optional according to the docs for Django 1.10 I'm running Django 1.10 + Python 3.5 -
Django extends template issue
Okay so I have my index.html file which has a file called info.html which exntends from the index.html file but it isn't quite working currently. Here's my code: index.html <body> {% include "home/quote.html" %} {% include "home/intro.html" %} {% block content %} {% endblock %} {% include "home/projects.html" %} {% include "home/goals.html" %} </body> info.html {% extends "home/index.html" %} {% block content %} <section class="info-section"> <div class="info-section_content"> {% include "home/includes/info-content.html" %} </div> </section> {% endblock %} -
Register admin models using django-polymorphic
I am converting existing models/admin over to django-polymorphic. I think I have the models and migrations done successfully (at least, it's working in the shell) but I can't get the admin to work. I'm finding the documentation a little fuzzy, but I think I've followed it correctly. class LibraryItemAdmin(PolymorphicParentModelAdmin): base_model = LibraryItem child_models = (Whitepaper) class LibraryItemChildAdmin(PolymorphicChildModelAdmin): base_model = LibraryItem class WhitepaperAdmin(LibraryItemChildAdmin): form = LibraryForm base_model = Whitepaper I don't understand the issue: Traceback: File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 108. response = middleware_method(request) File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/middleware/common.py" in process_request 74. if (not urlresolvers.is_valid_path(request.path_info, urlconf) and File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in is_valid_path 646. resolve(path, urlconf) File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve 521. return get_resolver(urlconf).resolve(path) File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve 365. for pattern in self.url_patterns: File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns 401. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module 395. self._urlconf_module = import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/srv/www/urls.py" in <module> 349. url(r'^admin/', include(admin.site.urls), name='admin'), File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in urls 291. return self.get_urls(), 'admin', self.name File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in get_urls 275. url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)), File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in urls 631. return self.get_urls() File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/polymorphic/admin/parentadmin.py" in get_urls 283. self._lazy_setup() File "/root/.virtualenvs/divesite/local/lib/python2.7/site-packages/polymorphic/admin/parentadmin.py" in _lazy_setup 92. self._compat_mode = len(child_models) and isinstance(child_models[0], (list, tuple)) Exception Type: TypeError at /admin/library Exception Value: object of … -
Django Rest Framework invalid username/password
Trying to do a simple 'GET' wih admin credentials returns "detail": "Invalid username/password." I have a custom user model where I deleted the username, instead I use facebook_id : USERNAME_FIELD = 'facebook_id' I tried changing the DEFAULT_PERMISSION_CLASSES: ('rest_framework.permissions.IsAuthenticated',), -- doesn't work! ('rest_framework.permissions.IsAdminUser',), -- doesn't work! The only one that works is: ('rest_framework.permissions.AllowAny',), But I do not want that, since I'm building an API for a Mobile App I also declared a CustomUserAdmin model and CustomUserCreationForm , apparently this was not the problem Help me understand what needs to be done to fix this annoying problem, I'm guessing it might have something to do with Permissions/Authentication or the fact that I CustomUserModel.. Also, let me know if there is a better way for a mobile app client to authenticate to the api -
django - validate model with ForeignKey
I have two models class MainThing(models.Model): ... total_amount = models.IntegerField() class SubThing(models.Model): main_thing = models.ForeignKey(MainThing, related_name='subthings') sub_amount = models.IntegerField() For various reasons, I need the total_amount equal to the sum of sub_amount for all SubThings linked to the same MainThing (yes, I need the redundancy). I am trying to write a validator for this, and as I am using django-rest-framework and the admin site and possibly standard views/forms, I would like to write the validator once only, which I understand means ModelForm.clean() doesn't do the trick. I tried putting this in MainThing.clean() but then I don't have access to the SubThings (self.subthings.count() gives me 0 when creating new objects) so I don't know how to calculate the sum. My best option at this point seems to be SubThing.clean() but then I need to test if we are adding or changing an object, which becomes ugly, and error messages are not produced at the right level (they should come at main level, not sub). What is the proper way to ensure consistency of my data in this scenario? I want to throw a ValidationError if my tests fails, and ideally not leave the database in a half saved state. I will … -
URL query parameters are not processed in django rest
views.py class my4appCompanyData(generics.ListAPIView): serializer_class = my4appSerializer def get_queryset(self,request): """Optionally restricts the returned data to ofa company, by filtering against a `id` query parameter in the URL. """ queryset = companies_csrhub.objects.all() #url_id = self.request.query_params.get('id', None) url_id = request.GET.get('id', None) return url_id if id is not None: queryset = queryset.filter(id=url_id) elif id is ALL: queryset = companies_csrhub.objects.all() else: queryset = "Error data not found" return queryset urls.py router.register(r'api/my4app/company/$', views.my4appCompanyData.as_view(),base_name="company") URL used for cheking : mywebsite/api/my4app/company/?id=100227 Planning to add multiple filters with default values but not working. Please help. -
Virtualenv and Pip hanging forever
I am running a django project with a virtualenv that was working completely fine up until this afternoon. I went to run source my-env/bin/activate and it seemed to activate (it gave me the usual command prompt), but when I tried python manage.py runserver it said it could not locate django. I ran a python script and tried to import django and sure enough it said there was no module named django. So I removed this virtualenv and created a new one and did a pip install -r requirements.txt. It was then I noticed that pip was hanging forever and upon type ^C it would give a long traceback which I will provide below. Once this happened I tried once again to delete the virtualenv and start over only now when I typed virtualenv new-env it would hang on "Installing setuptools, pip, wheel..." and also gave a long traceback upon entering ^C. I have looked all over the online forums and tried everything to fix this and nothing seems to be working. I am incredibly pissed because now I am unable to work on my app. If anyone has any ideas on how to fix this I would really appreciate it. … -
Can not write proper filtering queryset
There is such content type model: class CTModel(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') sport = models.ForeignKey(SportTypes) QuerySets: user_type = ContentType.objects.get_for_model(UserProfile) current_sport = Sports.objects.get(name='Football') rest_sports = Sports.objects.exclude(name__in=RANDOM LIST OF GAMES) # Here I want to get all users who play 'Football' users_play_football = CTModel.objects.filter(content_type=user_type, sport=current_sport) # Here I want to get all users, who play Football, but does not play any other games from 'rest_sports' users = users_play_football.exclude(sport=rest_sports) As a result, if a user plays 'Football' and any other game from rest_sports, I expect to get users empty, but it is not! I mean I want to get users empty in case if my user plays just Football. Where is my mistake? -
How to access variable from html/python to JavaScript?
We have a project setup implemented in Django and we're trying to create a search function. Currently, we pass our database of users from view.py to our .html file (view.py code below) def search(request): template_name = "search/search_it.html" users = models.Profile.objects.all() context = {'users': users} return render(request, template_name, context) Inside of our html code is where we are having issues. We are able to read our passed in users as below. {% if users %} <ul> {% for user in users %} <!-- <script> var username = user.slug --> Does not recognize user object document.getElementById("a1").value = username; </script> --> <a id="test" value="/users/{{user.slug}}"></a> {% endfor %} </ul> {% endif %} Our issue is that we would like to compare the search input against each passed in user's name. Our html file uses a onclick button into javascript. We have decided to try to tackle this various ways including: Use the javascript value outside of the - Did not work for obvious scope reasons Try to load the names into strings and then grab each name inside of the javascript - Messy and not proficient and (what we would like to do) Load each user into a javascript array that can be used … -
Django app and HTTPS
I am kinda new to this and I looked at other threads but sadly I found nothing similar. I am trying to access my Django app through https by using nginx+ uwsgi. The problem that I am having is that I cannot install uwsgi on my laptop as I am using windows. I am also planning on dockerizing the whole thing, so can you as well give me some tips for doing that. I have already got my SSL key + cert using OpenSSL. -
Cannot run Django development server
I'm new to Django and have gone through the recommended installation (set up for GeoDjango) and am now going through the general django tutorial to get an idea of how it works. IN the tutorial https://docs.djangoproject.com/en/1.10/intro/tutorial01/, it tells you to try and run the django development server with python manage.py runserver but when I do I get an error System check identified no issues (0 silenced). Unhandled exception in thread started by .wrapper at 0x04E20300> Traceback (most recent call last): File "C:\Python35\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection self.connect() File "C:\Python35\lib\site-packages\django\db\backends\base\base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "C:\Python35\lib\site-packages\django\db\backends\postgresql\base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "C:\Python35\lib\site-packages\psycopg2__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) psycopg2.OperationalError: fe_sendauth: no password supplied If anyone could shed any light on why this might be happening that would be extremely helpful. Thanks. -
AH00112: Warning - Centos 6 / Apache 2.4 / Django 1.9 / mod_wsgi 3.5 / python 2.7
I have a dedicated server with GoDaddy. I seem to have successfully set up everything properly but I can't seem to figure out why I'm getting this issue: When I restart apache: [root@sXXX-XXX-XXX-XXX /]# /scripts/restartsrv httpd I get this: AH00112: Warning: DocumentRoot [/usr/local/apache/var/www/<my_django_project>] does not exist AH00112: Warning: DocumentRoot [/usr/local/apache/var/www/<my_django_project>] does not exist AH00112: Warning: DocumentRoot [/usr/local/apache/var/www/<my_django_project>] does not exist I never specified a path of /usr/local/apache/var/www/<my_django_project> ??? It seems to just append my var/www/<my_django_project> to /usr/local/apache ... not sure why My httpd.conf file: ... a bunch of pre configured goDaddy stuff I'm guessing here ... LoadModule wsgi_module /usr/local/apache/extramodules/mod_wsgi.so AddHandler wsgi-script .wsgi <VirtualHost XXX.XXX.XXX.X:80> ServerName XXX.XXX.XXX.XXX ErrorLog /var/log/httpd/error.log # DocumentRoot /public_html/ ServerAdmin admin-noreply@mysite.com Alias /favicon.ico /var/www/<my_django_project>/static/favicon.ico Alias /static /var/www/<my_django_project>/static <Directory /var/www/<my_django_project>/static> Require all granted </Directory> Alias /media /var/www/<my_django_project>/media <Directory /var/www/<my_django_project>/media> Require all granted </Directory> WSGIDaemonProcess <my_django_project> python-path= /var/www/<my_django_project>:/var/www/<my_django_project>/<my_django_project>:/var/www/<my_django_project>/<my_django_project_site>:/usr/local/lib/python2.7/site-packages WSGIProcessGroup <my_django_project> WSGIScriptAlias / /var/www/<my_django_project>/<my_django_project>/wsgi.py <Directory /var/www/<my_django_project>/<my_django_project>> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> ... more stuff already in the conf file ... When I go to XXX-XXX-XXX-XXX:80 in my internet browser it told me it can't find .htaccess file. But now it's just redirecting me to http://XXX.XXX.XXX.XXX/cgi-sys/defaultwebpage.cgi Any help would be much appreciated -
Use my phpBB db for a Django app (novice programmer)
I have a website with phpBB forums that I have used for a while. I was wondering how I can use the phpBB's MySQL database as a central user account system that I can also use for any Django apps on my website (for registration/login). I understand this may come off as extremely vague. I would appreciate any help! -
Django SSO JWT Validation
I'm hitting an SSO provider and when it's all said and done, I have an id token and access token. The SSO provider has an endpoint that verifies the tokens. My question/concern is how do I store these tokens in django? Do I store them in the session? Database? And do I really need hit the verification endpoint for every page request? -
show children in current page Django
Hi everyone using Django CMS, I have a menu like this Home (home-template.html) page1 (page.html) -Subpage 1.1 (page.html) -Subpage 1.2 (page.html) page2 (page.html) -Subpage 2.1 (page.html) -subpage 2.2 (page.html) In my project I have a home-template.html page that I use for my home page, the rest of my page use page.html to show the data When I click page1 I render page.html, in this case page1 has subpage so I want to show this subpage like a list. but if I click in Subpage1.1 I want to show different info .. so I try to do something like this.. if (current page has child): show item submenu else: # show different for this I have something like this {% extends "base.html" %} {% load cms_tags menu_tags %} {% block title %}{% page_attribute "page_title" %}{% endblock title %} {% block content %} {% placeholder "content" %} {% for child in children %} {{child.title}} <br> {% endfor %} {% endblock content %} But this don't show me nothing, because children is empty. How to now if a current page has children!! Thank in advance! -
Apache/Django Install: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit
I am using Django 1.9 and python 2.7 on centos7 I am getting the following error ONLY when trying to use Apache with Django. RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I do NOT get the error using the Django web-server, my application works fine under the Django web-server, but I have read not to use the Django web-server but Apache instead. I have run into multiple issues trying to get apache to work with django, and have found solutions to all of the preceding issues, but cannot resolve this one. Here are my installed apps with "django.contrib.contenttype" in the list in this order: 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'admin_alerts', 'admin_dq_metrics', 'admin_db_conn', 'admin_file_conn', 'admin_application', 'admin_process', 'admin_src_status_chk', 'admin_scheduler_template', 'export_to_db', 'export_to_file', 'migrate_to_prod', 'migrate_to_stg', 'migrate_to_dev', 'tableau_tde', 'ingest_file', 'ingest_db', 'scheduler', 'dq_entity_cross_ref', 'high_water_column_ref', 'process_control', 'difa_login', 'admin_create_user', 'update_export_ingest_data', 'admin_add_user', 'django.contrib.sites', Thanks... -
Cannot click button when using sweet-alert with selenium
I'm trying to run a test that requires to confirm a sweetalert popup. I've tried waiting for the modal to be visible but is still not working. On the snapshot the modal is still showing. from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys from students.browser import wait from . import browser class ArchiveSupervisorTest(browser.SignedInTest): def test_can_archive_supervisor(self): self.get(self.live_server_url + '/supervisor/') btn = self.e_id('archive-tutor-' + str(self.supervisor_1.pk)) self.assertIn('Archive', btn.text) btn.click() browser = self.b element = WebDriverWait(browser, 10).until( EC.visibility_of_element_located((By.CLASS_NAME, 'showSweetAlert')) ) btn = self.e_class('confirm') btn.click() self.save_snapshot() btn_name = 'todo-done-' + str(self.supervisor_2.pk) element = WebDriverWait(self.b, 10).until( EC.visibility_of_element_located((By.CLASS_NAME, btn_name)) ) # line 38 btn = self.e_class(btn_name) btn.click() Here's the error message: /students/selenium_tests.py", line 38, in test_can_archive_supervisor EC.visibility_of_element_located((By.CLASS_NAME, btn_name)) line 80, in until raise TimeoutException(message, screen, stacktrace) TimeoutException: Message: -
Deploying Django With AWS
So I am trying to deploy my django app(which mostly has REST Apis) but when I use Amazon CLI, I end up having Fedora instance, while I want to use Ubuntu instance. So I tried to do this, I made an ubuntu instance, made a repository of my code, installed git on ubuntu and cloned the code from git to ubuntu. Next thing, I installed all the requirements.txt dependencies and everything is in virtualenv and working fine. But here's the catch, python manage.py runserver runs it on localhost(not really surprising). So the question is, how to serve those apis(not on localhost)? -
GET variables with Jade in Django templates
I use Jade (pyjade) with my Django project. For now I need to use static template tag with GET variable specified - something like following: link(rel="shortcut icon", href="{% static 'images/favicon.ico?v=1' %}"). But I get /static/images/favicon.ico%3Fv%3D1 instead of /static/images/favicon.ico?v=1 Why it happens and how can I fix this? Thanks in advance! -
How do I add several books to the bookstore in the admin form
In django, imagine i have a model book, and a model bookstore which has a foreign key to book model. On the django admin,I added like 10 books, and on the bookstore I want to assign multiple books to this one bookstore. How do I do this ? Because even with foreignKey, while editing the bookstore, i can only choose one book... class BookStore(models.Model): name = models.CharField(max_length=100) class Book(models.Model): name = models.CharField(max_length=100) store = models.ForeignKey(BookStore, null=True) -
Gmail authentication error when sending email via django celery
TL;DR: I get a SMTPAuthenticationError from Gmail when trying to send emails using Celery/RabbitMQ tasks from my Django app, despite the credentials passed in are correct. This does not happen when the emails are sent normally, without Celery. Hi, I am trying to send email to a user asynchronously using Celery/RabbitMQ in my Django application. I have the following code to send the email: from grad.celery import app from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import Context from grad import gradbase from time import sleep from grad import settings @app.task def send_transaction_email(student_data, student_email): html_email = get_template('grad/student_email.html') context = Context({ 'name': student_data['name'], 'university': student_data['university'], 'data': student_data, 'shorturl': gradbase.encode_graduation_data(student_data) }) msg = EmailMultiAlternatives('Subject Here', 'Message Here', 'myrealemailaddress@gmail.com', [student_email]) msg.attach_alternative(html_email.render(context), "text/html") msg.send() When I call the method normally: tasks.send_transaction_email(entry, stud_email) The emails are sent fine, but if I delegate the call to a Celery task like so: tasks.send_transaction_email.delay(entry, stud_email) I get the following trace: Traceback (most recent call last): File "/Users/albydeca/Gradcoin/venv/lib/python2.7/site- packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/Users/albydeca/Gradcoin/venv/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/Users/albydeca/Gradcoin/grad/tasks.py", line 27, in send_transaction_email msg.send() File "/Users/albydeca/Gradcoin/venv/lib/python2.7/site-packages/django/core/mail/message.py", line 303, in send return self.get_connection(fail_silently).send_messages([self]) File "/Users/albydeca/Gradcoin/venv/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 102, … -
How to select by WEEK and count it in postgresql and Django
I'm trying to select by week and counting how many tickets were sold on that week. i select the tickets using EVENT ID. WHERE EVENT ID 148 SAMPLE DATA: TICKETS TABLE "General";0;"2016-09-02 17:50:45.644381+00" "General";0;"2016-09-03 21:05:54.830366+00" "General";0;"2016-09-02 18:21:33.976451+00" "Early Bird";500;"2016-09-09 19:15:33.721279+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "Post Secondary Student";1000;"2016-09-06 14:46:53.90927+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "General";0;"2016-09-01 23:50:05.034436+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "Post Secondary Student";1000;"2016-09-06 14:46:53.90927+00" "Post Secondary Student";1000;"2016-09-06 14:46:53.90927+00" "General";0;"2016-09-03 18:39:15.571188+00" "General";0;"2016-09-07 20:14:35.959517+00" "General";0;"2016-09-03 21:33:04.349198+00" "General";0;"2016-09-07 18:21:22.220223+00" "General";0;"2016-09-01 23:34:55.773516+00" "General";0;"2016-09-01 23:42:15.498778+00" "Early Bird";500;"2016-09-09 19:15:33.721279+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "RSVP";0;"2016-09-27 21:27:33.378934+00" "RSVP";0;"2016-09-14 22:23:04.922607+00" "RSVP";0;"2016-09-14 22:23:04.922607+00" "General Admission";0;"2016-09-23 15:35:54.972803+00" "General Admission";0;"2016-09-23 15:35:54.972803+00" "RSVP";0;"2016-09-14 22:23:04.922607+00" "RSVP";0;"2016-09-14 22:23:04.922607+00" "General";1000;"2016-09-09 19:15:33.72771+00" "General Admission";0;"2016-09-23 15:35:54.972803+00" "General Admission";0;"2016-09-23 15:35:54.972803+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "RSVP";0;"2016-09-14 22:23:04.922607+00" "RSVP";0;"2016-09-14 22:23:04.922607+00" "General Admission";0;"2016-09-23 15:35:54.972803+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "Youth";0;"2016-09-06 14:46:53.903704+00" "General Admission";0;"2016-09-23 15:35:54.972803+00" "General Admission";0;"2016-09-23 15:35:54.972803+00" "Free Admission";0;"2016-10-03 19:12:12.965369+00" "Free Admission";0;"2016-10-06 19:00:25.926406+00" "Free Admission";0;"2016-10-06 19:00:25.926406+00" Any suggestions how i would achieve that? I DID THIS TO FIND AND COUNT BY DAY: Ticket.objects.filter(event_id=event_id, event_ticket_id=ticket_type.id, refunded=False).extra(where=('created',), select={'date_sold':'date(created)'}).values('date_sold').annotate(sold_count=Count('id')) but could not do by week. Thank you -
How to filter objects in mongoengine using 'LIKE' statement?
I have following json structure in my mongodb. { "country": "spain", "language": "spanish", "words": [ { "word": "hello1", .... }, { "word": "hello2", .... }, { "word": "test", .... }, ] } I am trying to get all the dictionaries inside 'words' list which have particular substring matched. For example, If I have a substring 'hel', then how should I query my document using mongoengine that gives two dictionary with word : 'hello1' and 'hello2' The following query works only for matched word not with the substring. data = Data.objects.filter(words__match={"word":"hel"}) // data is empty in this case([]) -
django: how to know if a model is created with a m2m field not None
So basically I am trying to override the save method of a model to tell if a certain non-required field, which is a m2m field, is specified. If so, then update one of its own Boolean field to True. Currently I have something like this: def save(self, *args, **kwargs): super(Model, self).save(*args, **kwargs) if Model.objects.filter(id = self.id, m2mField = None).exists(): Model.objects.filter(id = self.id).update(BooleanField = True) And this is not working for me now. I don't really care what is in the m2m field, just trying to know if that field is specified by user when creating this instance. TIA -
django url parameters as form default value
I have a search form class PostSearchForm(forms.Form): keyword = forms.CharField(label=_('Search the Courses')) def __init__(self,*args,**kwargs): self.request = kwargs.pop('request', None) super(PostSearchForm,self).__init__(*args,**kwargs) raise Exception(self.request) # This returns none categories = Category.objects.filter(status=True) self.fields['categories'] = forms.ModelChoiceField(queryset=categories, widget=forms.SelectMultiple(attrs={'class': 'some-class'})) Whenever search is made I have a build a form with default value as what they have searched, so what I tried is get the url parameters in form init and set the value but it was returning None due to some mistake. Can any one tell me where I am wrong