Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use StreamField editor outside admin?
I ran into problems trying to build a StreamField-based WYSIWYG editor. I want users to write their articles without giving them access to the admin panel. Is it even possible? -
Django Form ajax post request return 405 Method not allowed
I'm working on a Django(1.10) project in which i'm sending an ajax post request to a view but it returns 405 Method not allowed error. Here's my urls.py: urlpatterns = [ url('admin/', admin.site.urls), url(r'$', TemplateView.as_view(template_name='Unmundonuevo/index.html')), url(r'^contact/$', ContactFormView.as_view, name='contact'), ] Here's my HTML form: <form method="post" id="contactForm"> {% csrf_token %} <div class="form-group"> <input type="text" name="name" class="form-control input-field" placeholder="Name" required=""> <input type="email" name="email" class="form-control input-field" placeholder="Email ID" required=""> <input type="text" name="subject" class="form-control input-field" placeholder="Subject" required=""> </div> <textarea name="message" id="message" class="textarea-field form-control" rows="4" placeholder="Enter your message" required=""></textarea> <button type="submit" id="btn" value="Submit" class="btn center-block">Send message</button> </form> Here's my ajax: $(document).on('submit', '#contactForm', function (e) { e.preventDefault(); var data = new FormData($('#contactForm').get(0)); console.log(data); $.ajax({ type: 'POST', url: '{% url 'contact' %}', data: data, processData: false, contentType: false, success: function ($data) { console.log('Succcess'); $('#success').attr('hidden', false); } }); }); Here's my forms.py: class ContactForm(forms.Form): name = forms.CharField(max_length=255, required=True) email = forms.EmailField(max_length=255, required=True) subject = forms.CharField(max_length=255, required=True) message = forms.Textarea() And, here's my views.py: class ContactFormView(FormView): def post(self, request, *args, **kwargs): if request.method == 'POST': post_data = request.POST.copy() form = ContactForm(post_data) if form.is_valid(): print('valid') pass else: print('not valid') pass It returns: Method Not Allowed (POST): /contact/ Help me, please! Thanks in advance! -
Not able to connect to SQL Server 2012 from current version of DJango and Python
I am trying to connect to SQL server 2012 using Pyodbc and DJango framework but the version of Django is 2.1. Now, when I try to connect using below code when I only have Pyodbc installed then the below code doesnot run. DATABASES = { 'default': { # 'ENGINE': '{ODBC Driver 11 for SQL Server}', Tried this as well but it did not work. 'ENGINE': 'sql_server.pyodbc', 'NAME': 'MY_DATABASE', # 'HOST': 'XXX.XX.XXX.XXX', Tried this as well but it did not work. 'SERVER': 'XXX.XX.XXX.XXX', # 'HOST': 'SQLSERVER_InstanceName', 'PORT': '', 'USER': 'SQLSERVERUSER', 'PASSWORD': 'USER's PASSWORD', 'DATABASE': 'MY_DATABASE', # 'Trusted_Connection': 'Yes', # 'OPTIONS': { # 'driver': 'ODBC Driver 11 for SQL Server', # } }, } But when I install django-pyodbc-azure and try to run the above code by running python manage.py inspectdb command, it works. But the problem with using django-pyodbc-azure is that it downgrades the current version of django to 2.0.8 version - which I do not want. I do not want to use FreeTDS or Pymssql. I want to go with pyodbc only. Can someone please suggest some way for this? -
AttributeError: module 'django.contrib' has no attribute 'sessions'
This app works fine in my development environment, but on my PythonAnywhere instance there seems to be an issue with Django. Any idea what could cause this? Traceback (most recent call last): File "/home/cvcexport/genius/genius/local/lib/python3.5/site-packages/django/apps/config.py", line 118, in create cls = getattr(mod, cls_name) AttributeError: module 'django.contrib' has no attribute 'sessions' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/cvcexport/genius/genius/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/cvcexport/genius/genius/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/cvcexport/genius/genius/local/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/cvcexport/genius/genius/local/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/cvcexport/genius/genius/local/lib/python3.5/site-packages/django/apps/config.py", line 123, in create import_module(entry) File "/home/cvcexport/genius/genius/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'django.contrib.sessions' -
Django allauth in admin instead of default user
I'm using Django 2 and have implemented user authentication using django-allauth plugin. It is working fine from the frontend side, but the users are to be created by the superuser, therefore I need same integration in admin panel also. As of now, Django-admin has default users model with username and password field but according to django-allauth, I'm using the only email and thus I want the user registration fields to be. first_name last_name email password Could not understand how to implement django-allauth in the admin panel. -
Select a record in Django: filtering foreign key using a query set
I have three (relevant) classes: groups (Group A, Group B, etc), topics (topics of discussion), and GroupMember (a list that links users to groups). Now, each topic is linked to one or more groups in which it will be posted. But, at the same time, users can subscribe to a topic (subscriptions field). See below the outline: class Group(models.Model): name = models.CharField(max_length=255) members = models.ManyToManyField(User, through='GroupMember') class Topic(models.Model): name = models.CharField(max_length=255) groups = models.ManyToManyField(Group, related_name='topics') subscriptions = models.ManyToManyField(User, related_name='subscribed_to') class GroupMember(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) start = models.DateTimeField(auto_now_add=True) end = models.DateField(null=True, blank=True) Now I would like to select a topic, and then get a list with all the people who are part of that group. I tried this: topic = Topic.objects.get(1) members = GroupMember.objects.filter(group=topic.groups) But this yields this error: int() argument must be a string, a bytes-like object or a number, not 'ManyRelatedManager' So my question is: is there a way to query GroupMembers by selecting a group, based on a queryset (which is what topic.groups is I guess), instead of an integer? -
Django / React Router DOM - Landing on a url not specified in django
I'm building an app with django as the backend api and react as the frontend framework. When landing on an empty pathname url such as www.fakeapp.com/ django shows a frontend app view which renders an index page built with react. Inside the react SPA I have <Link>s which update the <BrowserRouter>s <Route>s and might send you to the path /user/register (which is working fine). However, if I refresh the page with the new pathname www.fakeapp.com/user/register django doesn't recognize the url and throws an error. I'm not sure the best path to take here since this is my first django project and my first time using react-router-dom. Should I specify more/different urlpatterns in the urls.py file for my frontend app, redirect back to the index, or something else? I can post any code needed. -
order of matching regex in named group urls in django
I'm making a blogging website with django. I'm making use of slug to identify a particular article. I'm making these blogs for 3 different fields namely sketches, cakes, and rangolis. But the problem here is, the regex of slug for urls of these three is coming to be the same. I've also named these urls for the ease but somehow can't control the order of matching the three. It is working for the named group regex of the url which is written first in the url file. I'm providing the necessary files below. My main website name is 'website' and the app name is'art'. For the order of named group urls given below the error is 'Rangoli matching query does not exist'. So only the first named group url is working. Can anyone help me resolve this. Thanks in advance! art/urls.py url(r'list_sketches.html$', views.sketches_list, name='sketches_list'), url(r'list_rangolis.html$', views.rangolis_list, name='rangolis_list'), url(r'list_cakes.html$', views.cakes_list, name='cakes_list'), url(r'^(?P[\w-]+)/$', views.rangolis_detail, name='rangolis_detail'), url(r'^(?P[\w-]+)/$', views.sketches_detail, name='sketches_detail'), url(r'^(?P[\w-]+)/$', views.cakes_detail, name='cakes_detail'), art/views.py def sketches_list(request): sketches = Sketch.objects.all().order_by('-date') return render(request, 'art/list_sketches.html', {'sketches':sketches}) def sketches_detail(request, slug): sketch = Sketch.objects.get(slug=slug) return render(request, 'art/detail_sketches.html', {'each':sketch}) list_sketches.html {% extends "me/base_layout.html" %} {% block content %} {% for each in sketches %} <h1><a href="{% url 'art:sketches_detail' slug=each.slug %}"> β¦ -
Displaying image from django.models.ImageField in a template
I am trying to display an image from a django model in a template. I am using Django 2.0 and Python 3.5 Project Structure . βββ db.sqlite3 βββ foo β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β βββ models.py β βββ __pycache__ β βββ templates β βββ tests.py β βββ views.py βββ manage.py βββ media β βββ uploads βββ scratchit β βββ __init__.py β βββ __pycache__ β βββ settings.py β βββ urls.py β βββ wsgi.py βββ uploads βββ images Here are the relevant code snippets: scratchit/settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+-fyu+u8ao0fk#o^%*wiec8l^m0h6l9bqff+#5)@67h7v_jtdp' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'foo.apps.FooConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'scratchit.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates"),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION β¦ -
Django how to use webhook in django and send data to zapier?
I am beginner in django. i read the docuemntation of rest api. how to send my model detail to zapier and how to make webhook and configuration? kindly help me -
django How to execute a function asynchronously i.e, handover a task to a sub process and return response
I am using django 2.0 and python 3.6. The user registration includes sending of a verification mail. And this mail sending process is taking longer and the user is kept waiting. What I need?: If the user registration form is valid, mailing details are sent to another task handler and regardless of whether the mail is sent or not, the function must resume and return a response. def new_user_registration(request): form = CustomUserCreationForm(request.POST or None) if form.is_valid(): user = form.save() send_verification_mail(user) #<= taking more time. return render(request, 'registration/signup.html') i.e, the send_verification_mail must be called asynchronously. How to achieve it? Note: I am new to django and python. -
Bootstrap Card with Navbar - How to Load New Content without Loading New Page?
I'm working with Django to build a simple website, and in one of my my pages, analysis.html, I call the Twitter API to load some data. In analysis.html, I have this card that I got from Bootstrap's components: <div class="card text-center" style="width: 800px;"> <div class="card-header"> <ul class="nav nav-pills card-header-pills"> <li class="nav-item"> <a class="nav-link" href="#buttona" style="color:#1DA1F2">Content A</a> </li> <li class="nav-item"> <a class="nav-link" href="#buttonb" style="color:#1DA1F2">Content B</a> </li> </ul> </div> <div class="card-body"> <h5 class="card-title">Content A</h5> <p class="card-text"> // Content A Stuff </p> </div> </div> There's 2 buttons, Content A and Content B, and upon clicking Content A I'd like the page to load content A stuff only inside the card, and similarly for content B. I'm fairly new to HTML, so my first thought was to just load a new page, say analysisA.html, upon someone clicking button A, and anaysisB.html upon someone clicking button B, where everything on the HTML template is the same except for content A/B. But this seems like bad coding, and it'd be calling the Twitter API unnecessarily, as all the necessary data is already called when analysis.html is opened. So, how should I go about swapping the content back and forth in the card only, while keeping everything β¦ -
DJANGO: AUTO ADD THE RESPECTIVE FOREIGN KEY VALUE IN CREATE VIEW
I am new to Django.. I am creating a CreateView with the following model. from django.db import models from uuid import uuid4 from django.core.validators import MinValueValidator,MaxValueValidator from questions.models import Question from django.urls import reverse class ExamPaper(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) name = models.CharField(max_length=300) for_class = models.PositiveSmallIntegerField(validators=( MinValueValidator(1),MaxValueValidator(12),)) date = models.DateField(null=True, blank=True) PARTS = ( ("A", "A"), ("B", "B"), ("C", "C"), ("D", "D"), ("E", "E"), ) part = models.CharField(max_length=1, choices=PARTS, null=True,blank=True) def __str__(self): return f"{self.name} ({self.get_part_display()})" def get_absolute_url(self): return reverse("exam_detail", args=[str(self.pk)]) class ExamQuestions(models.Model): exam = models.ForeignKey(ExamPaper,on_delete=models.SET_NULL, null=True, related_name="examquestions") question = models.ForeignKey(Question, on_delete=models.CASCADE,) marks = models.PositiveSmallIntegerField(validators=MaxValueValidator(20),),) def __str__(self): return self.question.question[:150] def get_absolute_url(self): return reverse("exam_detail", args=[str(self.exam.pk)]) I am trying to make a form using CreateView in which i can add Questions and marks to a ExamPaper.. I have allready created a CreatView using ExamPaper model and added a link in it to add questions.. What i want is that whenever i add questions the exam field gets assigned to that question. views.py class ExamCreateView(CreateView): model = ExamPaper template_name = "exam_new.html" fields = "__all__" class ExamQuestionsView(CreateView): model = ExamQuestions fields = "question", "marks", template_name = "exam_ques_new.html" I am able to get a form for both but in ExamQuestionView i have to select exam from β¦ -
How to implement TIMESTAMPDIFF() of MYSQL in Django
How can I implement TIMESTAMPDIFF(UNIT,EXPR_1,EXPR_2) of MYSQL in Django (as DB function) ? -
How I can to create form with cycle in Django?
I must to do hard form. with filter. I done it in html, but for save data from form fields and for good look of my code I think, that I must to do it in Django forms. my Model: class TagsEpisodes(models.Model): tag_type = models.ForeignKey('TagsTypes', models.DO_NOTHING) tag_id = models.AutoField(primary_key=True) episode = models.ForeignKey('Episodes', models.DO_NOTHING) tag_value = models.CharField(max_length=30, blank=True, null=True) class TagsTypes(models.Model): tag_type_id = models.AutoField(primary_key=True) tag_type = models.CharField(unique=True, max_length=50, blank=True, null=True) I must to write in form tagtype and for every tagtype write select with tag_value. screen, how it must to be: How I wrote it in Html: <form action="" method="get"> <div class="tag_select__block"> <input type="button" name="" class="delete_select_tag_type" value="ΠΡΠΌΠ΅Π½ΠΈΡΡ Π²ΡΠ΅"> <div class="tag_episodes_tag_type"> {% for tag_type in tag_types %} <div class="label_select_tag_value"> <label for="{{ tag_type.tag_type_id }}" class="tag_type_label">{{ tag_type.tag_type }}</label> <select class="select_tag_value" name="{{ tag_type.tag_type_id }}" id="{{ tag_type.tag_type_id }}" multiple="multiple"> <option id="+" value='0'></option> <option value='+'>+</option> <option value='-'>-</option> <option value='-/-'>-/-</option> <option value='+/+'>+/+</option> <option value='+/-'>+/-</option> <option value='-/+'>-/+</option> <option value='1'>1</option> <option value='2'>2</option> <option value='3'>3</option> <option value='4'>4</option> <option value='?'>?</option> </select> </div> {% endfor %} </div> </div> <input type='submit' value='Filter'/> </form> And I processed this form in views: class TagsEpisodesList(LoginRequiredMixin, PagedFilteredTableView, FormView): model = TagsEpisodes table_class = TagsEpisodesTable filter_class = TagsEpisodesListFilter formhelper_class = TagsEpisodesListFormHelper form_class = TagsEpisodesForm template_name = 'data_analysis/tags_episodes.html' login_url = β¦ -
Django's get_or_create method returning non-existent data
I have a model called Service where I have an object named Service1. I got the following at the shell: $ obj, created = Service.objects.get_or_create(name=u'Service1') $ obj <Service: Service1> $ obj.id 3 $ created False $ Service.objects.all() [<Service: Service1>] $ Service.objects.first().id 1 I checked the database and there is only one Service object which is the Service with id=1. Why is get_or_create retrieving an object that doesn't even exist? -
Reverse for 'calendar_create_event' not found. 'calendar_create_event' is not a valid view function or pattern name
Can anyone spot where im going wrong? the django error: Request Method: GET Request URL: http://127.0.0.1:8000/calendar/calendar/daily/calendar1/?year=2018&month=7&day=7 Template error: \schedule\templates\schedule\_daily_table.html, error at line 8 Reverse for 'calendar_create_event' not found. 'calendar_create_event' is not a valid view function or pattern name. 1 : {% load scheduletags %} 2 : <table class="table table-striped"> 3 : {% for slot in slots %} 4 : <tr> 5 : <td class="col-md-1"> 6 : <span class="time">{{ slot.start|time:"G:i" }}</span> 7 : {% if addable %} 8 : {% create_event_url calendar slot.start %} 9 : {% endif %} 10 : </td> 11 : <td class="col-md-4"> 12 : {% for occ in slot.occurrences %} 13 : <button type="button" class="btn {% if occ.cancelled %} btn-danger {%else%} btn-primary {% endif %}" data-toggle="modal" data-target="#{% hash_occurrence occ %}" {% if occ.event.color_event %} style="background-color: {{occ.event.color_event}};border-color:{{occ.event.color_event}}" {% endif %}> 14 : {% options occ %} 15 : {% title occ %} 16 : </button> 17 : {% include 'schedule/_detail.html' with occurrence=occ %} 18 : {% endfor %} Exception Type: NoReverseMatch at /calendar/calendar/daily/calendar1/ Exception Value: Reverse for 'calendar_create_event' not found. 'calendar_create_event' is not a valid view function or pattern name. function from scheduletags: @register.inclusion_tag('schedule/_create_event_options.html', takes_context=True) def create_event_url(context, calendar, slot): context.update({ 'calendar': calendar, 'MEDIA_URL': getattr(settings, 'MEDIA_URL'), }) lookup_context = β¦ -
Django sending order details to Twilio
I have a Django Saleor application that delivers an eCommerce store for a food takeaway service. I have a function called Validate_Order which returns a text representation of the order. I want to call this after the checkout process has been successful followed by a new piece of functionality that allows me to send the text representation to a Twilio number. Validate_Order Function (only which logs the text representation to the browser console def validate_order(request): if request.GET['id'] == str(1): order_no = request.GET['order_id'].strip() order_id = order_no[-3:] Nondescript_text = "01" Order_number = order_id token = Order.objects.get(pk=order_id) orders = Order.objects.confirmed().prefetch_related( 'lines__variant', 'fulfillments', 'fulfillments__lines', 'fulfillments__lines__order_line') orders = orders.select_related( 'billing_address', 'billing_address', 'user') order = get_object_or_404(orders, token=token.token) # item_qty = [] # item_name = [] # item_price = [] item_desc = [] for line in order: # item_qty.append(line.quantity) # item_name.append(line.product_name) # item_price.append(line.unit_price_gross.amount) item_desc.append(str(line.quantity) + ';') item_desc.append(line.product_name + ';') item_desc.append(str(line.unit_price_gross.amount) + ';') Delivery_charge = order.shipping_price.gross.amount Credit_card_handling_fee = 0 total = order.total.gross.amount Customer_verification_status = 4 Customer_name = order.billing_address.first_name + ' ' + order.billing_address.last_name Customer_address = order.billing_address.street_address_1 + ' ' + order.billing_address.street_address_2 + ' ' + order.billing_address.city + ' ' + order.billing_address.postal_code + ' ' + order.billing_address.country.name order_date_time = order.billing_address.delivery_time[:5] + ' ' + str(order.created) previous_order = "" order_detail β¦ -
`django.contrib.sites` migrations not applied during unit tests?
I'm trying to make and run some test in the application I'm working on. Yet I get the following error : django.db.utils.ProgrammingError: relation "django_site" does not exist` How could I get rid of it? Which made us think that the table didn't even exist. So a coworker suggested me to run the test command with -v2 : $ ./manage.py test partnership -v2 [125/1453] Creating test database for alias 'default' ('test_osis_local')... Operations to perform: Synchronize unmigrated apps: ajax_select, analytical, bootstrap3, ckeditor, dal, dal_select2, debug_toolbar, django_extensions, localflavor, messages, ordered_model, rest_framework, staticfiles, statici18n, test s Apply all migrations: admin, assessments, assistant, attribution, auth, authtoken, base, cms, contenttypes, dissertation, internship, osis_common, partnership, reference, sessions, sites, waffle Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying reference.0001_initial... OK Applying reference.0002_auto_20160414_1720... OK Applying reference.0003_decree_domain... OK Applying reference.0004_educationinstitution... OK Applying contenttypes.0002_remove_content_type_name... OK Applying base.0013_project_refactoring... OK Applying base.0001_initial... OK Applying base.0002_auto_20160122_1023... OK Applying base.0003_auto_20160122_1201... OK Applying base.0004_auto_20160122_1431... OK Applying base.0005_person_email... OK Applying base.0006_examenrollmenthistory... OK Applying base.0007_auto_20160209_1107... OK Applying base.0008_auto_20160209_1659... OK Applying base.0009_triggers_field_changed... OK Applying base.0010_auto_20160210_2255... OK Applying base.0011_offeryear_offer_parent... OK Applying base.0012_triggers_field_changed... OK Applying base.0014_auto_20160222_1124... OK Applying base.0015_auto_20160223_0921... OK Applying base.0016_auto_20160224_1039... OK Applying base.0017_person_language... β¦ -
django view - user passes test multiple conditions?
Im using the below to make sure a user has a custom permission before allowing them to run the view. however I would like to add multiple conditions, i.e. a user has_perm sites.can_view_mgmt or sites.can_view_finanical @user_passes_test(lambda u: u.has_perm('sites.can_view_mgmt')) is it possible to have an or in user passes test? Thanks -
Celery - signals.py not loaded / @task_postrun.connect not firing
I have two issues that may or may not be related. I have a signals.py inside my project/jobs app. This is the file: from celery.signals import task_postrun, after_task_publish @after_task_publish.connect def task_sent_handler(sender=None, headers=None, body=None, **kwargs): info = headers if 'task' in headers else body print('after_task_publish for task id {info[id]}'.format(info=info,)) @task_postrun.connect def task_postrun_handler(task_id=None, **kwargs): print('CONNECT', task_id) from project.jobs.models import JobModel, JOB_STATUS_CHOICES JobModel.objects.filter(task_id=task_id).update(status=JOB_STATUS_CHOICES.SUCCESS) task_sent_handler is fired while task_postrun_handler is not. Some other strange behaviour is that none of the above handlers are fired, unless I import signals.py in some other module. I have tried the following in settings.py but without any success: CELERY_IMPORTS = ('project.jobs', 'project.jobs.signals',) Task auto-discover is working with a tasks.py inside my project/jobs app. This is my celery config: CELERY_BROKER_URL = env('CELERY_BROKER_URL') CELERY_IMPORTS = ('project.jobs', 'project.jobs.signals',) CELERY_SEND_EVENTS = True CELERY_RESULT_BACKEND = env('CELERY_RESULT_BACKEND') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' Any suggestions as to why task_postrun may not be fired? Also, how should I be loading signals.py ? -
Case insensitive search in django
I'm trying to do a case insensitive search for a substring within a field in my model. My model: class doctor(models.Model): docid = models.AutoField(primary_key=True, unique=True) # Need autoincrement, unique and primary name = models.CharField(max_length=35) username = models.CharField(max_length=15) regid = models.CharField(max_length=15, default="", blank=True) photo = models.CharField( max_length=35, default="", blank=True) email = models.EmailField(default="", blank=True) phone = models.CharField(max_length=15) qualifications = models.CharField( max_length=50, default="", blank=True) about = models.CharField( max_length=35, default="", blank=True) specialities = models.CharField( max_length=50, default="", blank=True) department = models.CharField(max_length=50, default="ENT", blank=True) fees = models.FloatField(default=300.0) displayfee = models.IntegerField(default=0, blank=True) slotrange = models.CharField(max_length=50, blank=True) slotdurn = models.IntegerField(default=10) breakrange = models.CharField( max_length=50, default="", blank=True) slotsleft = models.CharField( max_length=50, default="", blank=True) def __str__(self): return self.name def Range(self): return self.slotrange def listslots(self): SlotRange = self.slotrange SlotDurn = self.slotdurn startime = SlotRange.split('-')[0] endtime = SlotRange.split('-')[1] sthr, stmin = SplitTimeString(startime) enhr, enmin = SplitTimeString(endtime) print(stamptoday(sthr, stmin)) print(stamptoday(enhr, enmin)) startstamp = stamptoday(sthr, stmin) endstamp = stamptoday(enhr, enmin) secdurn = SlotDurn*60 slotlist = [] for sec in range(startstamp, endstamp, secdurn): enttime = sec + secdurn myrange = ("%s - %s" % (HumanTime(sec), HumanTime(enttime))) slotlist.append(myrange) return slotlist Under the field 'name' in my mysql database, are two rows with values for name as 'Joel' and 'Jaffy Joel'. When I do the search like β¦ -
Combine jquery form validation and django internationalization
I am working in a project where we have 2 languages, and I validate a form with jquery. Everything works fine, except I am not able to translate the error messages for the form. I have tried using {% trans %} and sending the message as a context variable already translated with ugettext, but neither worked. There sure must be a way to do it. Any help would be great, thanks! Code: var formValid = {mail_num_valid: false, name_valid: false}; function checkValidation() { if (formValid.mail_num_valid == true && formValid.name_valid == true) { $('#submitButton').removeAttr("disabled"); } else { $('#submitButton').attr("disabled", "true"); } }; $('#{{ form.mail_or_num.id_for_label }}').on('input', function() { var mail_num = $(this).val(); function msg(content) { $('#mail_num_error').text(content).show(); }; function hide() { $('#mail_num_error').hide(); }; var num_exp = new RegExp('^[0-9]+$'); var mail_exp = /\S+@\S+\.\S+/ num_test = num_exp.test(mail_num); mail_test = mail_exp.test(mail_num); if (mail_test) { formValid.mail_num_valid = true; hide(); } else if(mail_num.length == 0) { formValid.mail_num_valid = false; hide(); } else if (num_test && 9 <= mail_num.length && mail_num.length <= 13) { formValid.mail_num_valid = true; hide(); } else if (mail_num.length < 5) { msg({% trans 'Too short to be a valid mail or number' %}); // This sends an error. formValid.mail_num_valid = false; } else if (num_test && mail_num.length β¦ -
How to get data that was displayed in template with django template language into different method
How can i access data, after i press button, that was displayed in my template from different method in views.py. Short example of what i am trying to achieve: TEMPLATE: (test.html) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% for each in my_list %} <p>each</p> {% endfor %} <a class="btn" href="url to cal second_method"></a> </body> </html> Views.py: def first_method(request, template='test.html'): context = { 'my_list': ["one","two","tree"] } return render( request, template, context ) def second_method(request): # i want to work with my_list here after pressing <a> # i want to be able to export it to excel for example What is the best way to do this. -
Get all Actions filtered by Verb with Django Activity Stream
I'm quite new to Django and Python, so maybe my Question might be stupid but.. I'm logging what users do on my page with Django-Activity-Stream. And now I'm trying to build a page where I'll have a nice graph showing me what users did depending on the action and date. So far so well, until now I did it with a raw sql query but since Django's not supposed to be used like this, I want to count actions filtered by the verb it's allocated to. My raw query looks like : cursor = connection.cursor() cursor.execute("SELECT COUNT(id) FROM actstream_action WHERE verb = %s " "AND '2018-06-01' <= timestamp AND '2018-06-30' >= timestamp", ['User created']) row = cursor.fetchone() return row[0] I hope somebody could help me! Thanks in advance