Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding functions to makemigration in Django (Elasticsearch Index)
I am trying to create a project that combines Django and Elasticsearch. What I want to do is create or update an Elasticsearch Index when a Django migrations file is created. The brute way would be to detect any changes in the migrations folder and execute a function that will create/update the Elasticsearch Index accordingly, but I want to create something that will directly respond to the makemigrations command, as that is more intuitive. Looking at the migrations doc in Django, I can't really find useful information on how the migrations file is created. Thank you for all the help. -
How to make a code that alters database in background Django
I'm making an elimination style voting website. People log in, vote for their least favorite participant, and at the end of the day the person with the most votes goes inactive. Almost everything works: The log in, the voting, etc. But I have no idea how to make a program that checks for the most votes and alters the database to change the status of a participant at a particular time without needing a user to enter the website. I don't even know where to put the code. And how would I make sure it's constantly running? The way I see it, views.py only works when a user goes to the URL, so if no one visited the website at the time of vote recopilation it wouldn't work, so that's a no no. I could make a script outside of the Django project that does this, and then run it with nohup &, but then I'd lose on the model notation and would have to make manual queries, plus I'm sure there's a better, more Django way to do this. Any solutions to this problem? Or maybe some direction you can point me in? -
Reservation message in django
I am making a chatbot using a messenger called KakaoTalk. I wrote a function that sends a message when the current request is received. However, I can not implement the function of sending notification characters in the morning. I need your help. Here is my code sample. def message(request): json_str = ((request.body).decode('utf-8')) received_json_data = json.loads(json_str) content = received_json_data['content'] data_will_be_send = { 'message': { 'text': connect_apiai.get_apiai(papago.get_papago(content)) } } return JsonResponse(data_will_be_send) How can I send JsonResponse without a request? -
Python - Basic validation of international names?
Given a name string, I want to validate a few basic conditions: -The characters belong to a recognized script/alphabet (Latin, Chinese, Arabic, etc) and aren't say, emojis. -The string doesn't contain digits and is of length < 40 I know the latter can be accomplished via regex but is there a unicode way to accomplish the first? Are there any text processing libraries I can leverage? -
Using database server in Docker container based architecture
Im learning Docker and for test purposes Im running a Django App in it. Everything is OK and running. But now i want to use database(Postgres) in my containerised architecture. As we know, If a container stops, All data will be reseted and because of that I can't put my database in container, Right? Im confused about this. Should I run database server outside of container? Then how App inside container should talk with that? Or I have to run database service in the container and read database dump files from external source? Im confused about architecture! Containers are just for Apps and codes no just database servers? Or I can use database inside the container? I love containers idea and i want to do my project as a package that runs everywhere... But when im using database server, is this possible? -
django TemplatSyntaxError at / when passing variable to html file
using django, i'm getting a blank page when executing this code {% block content %} {% for c in content %} <p1>{{c}}</p1> {% endfor %} {% endblock %} the page title is 'TemplatSyntaxError at' i'm new to html so it is likely a simple fix thank you. x -
Django - Celery 4.1 with django-celery-beat/rabbitmq : Nothing?
I followed the tutorial on http://docs.celeryproject.org/en/latest/ and when I started the daemonization with the init-script: celerybeat (with /etc/default/celeryd config file) [2017-11-19 01:13:00,912: INFO/MainProcess] beat: Starting... and nothing more after. Do you see what could I make wrong ? My celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oscar.settings') app = Celery('oscar') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Broker settings app.conf.broker_url = 'amqp://oscar:oscar@localhost:5672/oscarRabbit' # Load task modules from all registered Django app configs. app.autodiscover_tasks() some_app/tasks.py: from __future__ import absolute_import, unicode_literals from oscar import celery_app from celery.schedules import crontab from .models import HelpRequest from datetime import datetime, timedelta import logging """ CONSTANTS FOR THE TIMER """ # Can be changed (by default 1 week) WEEKS_BEFORE_PENDING = 0 DAYS_BEFORE_PENDING = 0 HOURS_BEFORE_PENDING = 0 MINUTES_BEFORE_PENDING = 1 # http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html # for schedule : http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#crontab-schedules @celery_app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(minute=2), set_open_help_request_to_pending ) @celery_app.task(name="HR_OPEN_TO_PENDING") def set_open_help_request_to_pending(): """ For timedelay idea : https://stackoverflow.com/a/27869101/6149867 """ logging.info("RUNNING CRON TASK FOR STUDENT … -
UserProfile as a foreign key in xadmin didn's dispaly option selection
class UserProfile(AbstractUser): nick_name=models.CharField(max_length=50,verbose_name='昵称') birthday=models.DateTimeField(verbose_name='生日',null=True,blank=True) gender=models.CharField(max_length=50,choices=(('male',u'男'),('female',u'女')),default=('male',u'男')) address=models.CharField(max_length=100,default=u'') mobile=models.CharField(max_length=11,null=True,blank=True) image=models.ImageField(upload_to='image/%Y/%m',default=u'image/default.png',max_length=100) class Meta: verbose_name=u'用户信息' verbose_name_plural=verbose_name def __unicode__(self): return self.username class UserCourse(models.Model): user = models.ForeignKey(UserProfile, verbose_name=u'用户') course = models.ForeignKey(Course, verbose_name=u'课程') add_time=models.DateTimeField(default=datetime.now, verbose_name=u'添加时间') class Meta: verbose_name = u'用户课程' verbose_name_plural = verbose_name the filter filed is search ,why is it option list? they are all foreign key, why the first line are search and second line are option? -
Ajax prost request return empty querydict
i'm trying to send a post request and authenticate a user based on that information. however even though i have checked the result from $('#sign_in').serialize() and it returns something like username=test&password=test it still returns <QueryDict: {}> when i run print(request.POST) inside my views.py. What am i doing wrong and why is it not passing the parameters? ajax function function logIn() { var username = $('#id_username').val(); var password = $('#id_password').val(); console.log($('#sign_in').serialize()) $('#sign_in_btn').text('Logger ind...'); $.ajax({ url: "/account/login/", type: "POST", dataType: 'json', contentType: 'application/json', data: $('#sign_in').serialize(), success: function (data) { console.log(data) }, error: function (error) { } }); } views.py def login(request): print(request.POST) if request.method == "POST": form = SignInForm(data=request.POST) response_data = {} if form.is_valid(): username = request.POST.get("username", False) password = request.POST.get("password", False) user = authenticate(username=username, password=password) auth_login(request, user) if user: response_data['success'] = True response_data['message'] = 'Brugeren er blevet oprettet!' else: #invalid case response_data['success'] = False response_data['message'] = 'Forkert brugernavn/kodeord. Prøv venligst en anden kombination eller tryk på glemt kodeord!' print(form.errors) return HttpResponse(json.dumps(response_data), content_type='application/json') else: form = SignInForm() return render(request, 'login.html', {'form': form}) -
django querysets in templates
I am trying to make specific queries by using some model entry fields. I have the following model entry: models.py class Work(models.Model): categories =( ('cat1', 'cat1'), ('cat2', 'cat2'), ('cat3', 'cat3'), ('cat4', 'cat4'), ('cat5', 'cat5'), ) title = models.CharField(max_length=200) description = RichTextUploadingField(config_name='awesome_ckeditor') date = models.DateTimeField(default=timezone.now) category = models.CharField(max_length=200, choices = categories, default = 'projects') thumb = models.ImageField(upload_to = 'works/thumbs', blank = True) content = models.FileField(upload_to = 'works/content_media', blank = True) published = models.BooleanField() def __str__(self): return self.title def get_absolute_url(self): return reverse("work_detail",kwargs={'pk':self.pk}) @property def thumb_url(self): if self.thumb and hasattr(self.thumb, 'url'): return self.thumb.url @property def content_url(self): if self.content and hasattr(self.content, 'url'): return self.content.url here is the view: views.py class WorksListView(ListView): template_name = 'template.html' model = Work def get_queryset(self): return Work.objects.filter(published=True).order_by('-date') and I am trying to query first by the category field then by entry in the following template: template.html {% for category in works_list.category %} <ul data-category-name={{category.name}}> {% for work in category.works %} <li data-thumbnail-path={{thumbnail.url}} data-url={{content.url}} > <div> <p class="gallery1DecHeader">{{work.title}}</p> <p class="gallery1DescP">{{work.description}}</p> </div> </li> {% endfor %} {% endfor %} what do I need to change? -
anomaly when overriding bootstrap in django
For the past two hours I've been trying to figure out a strange behavior when trying to override bootstrap in Django. At the beginning, without any custom css file, the result was this: output without any custom css file Then I created a custom css file: my_site/css/master.css .index-jumbotron { background-color: #006DB0; } #main-title { text-align: center; color: white; } It resulted in this: my_site/css/master.css output So far, so good. But now, if I change anything on that same file (even when putting !important and taking good care of the specificity system), the result is always the same as the image immediately above. However, when I indicate my template to point to another file my_site/css/master2.css or css/master.css, indeed the result is as I would have expected: my_site/css/master2.css output I can't get my head around this. Do you have any idea? Do you know if the package django-bootstrap3 could have anything to do with that? I installed it in between my two different version of the custom css file. -
How do you pass Django variables that are passed to an HTML page to modal that is included in that HTML page
I am passing a list of objects to an HTML page. On that HTML page, I can access those objects by writing something like: {{ item.name }} I also included a Bootstrap 4 modal on this HTML page with the following code: {% include 'my_modal.html' %} This modal only appears if a user clicks a button. When the user clicks that button and the modal appears, I want to be able to put {{ item.name }} in that modal, but it doesn't work. How can I use the same objects that I successfully passed to an HTML page in the modal that is included in that HTML page? -
How to use two different Django Form at the same template
If I have two forms: class UserProfileForm(ModelForm): prefix = 'user' class Meta: model = User fields = ('first_name', 'last_name', 'email', 'gender', 'bio', 'profile_photo', 'university', 'uni_email', 'bg_photo') class MentorProfileForm(ModelForm): prefix = 'mentor' class Meta: model = Mentor fields = ('first_name', 'last_name', 'email', 'gender', 'bio', 'profile_photo', 'university', 'uni_email', 'bg_photo', 'mentor_universities', 'mentor_calendly', 'mentor_countries', 'mentor_ability',) and I wanted to use a class based view, and send both forms to the template, class EditProfileView(UpdateView): model = User form_class = UserProfileForm form_class2 = MentorProfileForm template_name = 'site/edit_profile.html' def get_object(self, queryset=None): if self.request.user.is_authenticated(): try: mentor = Mentor.objects.get(username__iexact=self.request.user.username) return mentor except Mentor.DoesNotExist: return self.request.user else: raise Http404("User is not authenticated") def get(self, request, *args, **kwargs): try: self.object = self.get_object() except Http404: return HttpResponseRedirect('/login/') context = self.get_context_data(object=self.object) return self.render_to_response(context) def get_context_data(self, **kwargs): context = super(EditProfileView, self).get_context_data(**kwargs) if 'form' not in context: context['form'] = self.form_class(prefix='user') if 'form2' not in context: context['form2'] = self.form_class2(prefix='mentor') return context def post(self, request, *args, **kwargs): self.object = self.get_object() if 'form' in request.POST: form_class = self.get_form_class() form_name = 'form' else: form_class = self.form_class2 form_name = 'form2' form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(**{form_name: form}) in Template: {{ form.first_name }} {{ form2.first_name }} I can get in 2 forms like this, but the fields … -
Django SECRET KEY environmental variable not working in Elastic Beanstalk
In my settings.py I have SECRET_KEY = os.environ.get('SETTINGS_SECRET_KEY') In my Elastic Beanstalk environmental variables I have: SETTINGS_SECRET_KEY = 'my_secret_key' If I don't set up an alternative, i.e., SECRET_KEY = os.environ.get('SETTINGS_SECRET_KEY', 'abcde') then my app doesn't run and I get an error saying that the SECRET_KEY cannot be empty. -
python - ignore invalid keyword argument when usking **dict
I am using django and and etree for scraping xml content into a database. I want to use etree (root.attrib) to create a dict from the xml and then Model(**dict) to create a model instance in Django. I don't necessarily want all of the xml attributes in the database model, but I don't want to have to manually construct the dict (or the comma separated keyword argument list either) or manually remove the keys from the dict that are not in the model and hence are not valid keyword arguments to the constructor of the model instance. So I end up getting the error below when I have a field in the xml that is not a valid field in the model. Does anyone know of a method to get python in general (django orm model constructors specifically) to ignore kwargs if the are not valid for the function when passing arguments with **dict? Traceback (most recent call last): File "./load_games.py", line 189, in atbat = Atbat(**atbat_dict) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 555, in init raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'des' is an invalid keyword argument for this function -
2 words queryset request in Django for the same variable
If the user type "word1" in the form field of var1, I would like to do a query in the database considering the word1 + "word99"(as standard search), how can I do that considering my code bellow? I am new in django. Thanks a lot for the help def qrs_table(request): form = MyForm() query = {} if request.GET.get('Var1'): query['Var1'] = request.GET.get('Var1') if request.GET.get('Var2'): query['Var2'] = request.GET.get('Var2') results = Model.objects.filter(**query).distinct() qrs_table = MyTable(results) return render(request, 'app/page.html', {'form': form, 'qrs_table': qrs_table}) -
ValueError: invalid literal for int( ) with base 10: '262,400,000'
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database. But while migrating the app I'm getting this error: ValueError: invalid literal for int() with base 10: '262,400,000' Here's the traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/aggregator/WorldBank/management/commands/fetch_wb.py", line 60, in handle Projects.objects.create(**pdata) File "/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/python/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 962, in _do_insert using=using, raw=raw) File "/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/python/lib/python3.6/site-packages/django/db/models/query.py", line 1076, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1106, in execute_sql for sql, params in self.as_sql(): File "/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1059, in as_sql for obj in self.query.objs File "/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1059, in <listcomp> for obj in … -
Django can't find my static files
I can't for the life of me figure out why I django can't find my static files. My directory structure is like so: ├── projectname │ ├── appname │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── manage.py │ └── projectname │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── settings.cpython-36.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── static ├── templates └── virtualenv My appname/urls.py looks like this from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.home_page, name="home_page") ] The appname/views.py: from django.shortcuts import render def home_page(request): return render(request, 'home_page.html') The home_page view extends the base.html, at ./templates/base.html {% load staticfiles %} <html> <head> <title>Title</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'home_page.css' %}"> </head> <body> <div class="container"> {% block content %} {% endblock %} </div> </body> And the home_page.html at ./templates/home_page.html {% extends 'base.html' %} {% block content %} <p>TEXT</p> {% endblock %} Finally the css file at ./static/styles.css p { … -
How to get image source of a highcharts image in JS/Jquery to open it in new tab?
I would like to obtain the url of a highcharts (container) image by using JS/Jquery. However, I cannot find a solution for this.... Thank you in advance for your help! -
Show Form Only to Specific User on Django
I have a blog part within my project. It's something simple. It has only title and content for now.. Basically, it looks like Facebook post form: on top of the post lists (you can easily visualise) and my problem comes here: with {% if user.is_authenticated %} code line I can allow my form to be seen only by the registered user. That's fine, but as a registered user when I visit other users' pages I can still see the form there. But, no! I want to show it (or I want it to be seen) only to the active user on its own page. So, I shouldn't see the form of other users when I visit their pages. Shortly dear friends, my little post form must be visible only to an authenticated user on his/her own page, not to other users. How can I do it? my codes: My Model: class Posts(models.Model): user = models.ForeignKey('auth.user', verbose_name='Writer', related_name='posts') post_title = models.CharField(max_length=120, verbose_name='Title') post_content = models.CharField(max_length=240,verbose_name='Content') publishing_date = models.DateTimeField(verbose_name='PubDate', auto_now_add=True) My View : class AddPost(CreateView): model = Posts fields = ['post_title', 'post_content' ] success_url = '/directory/dashboard' def form_valid(self, form): form.instance.user = self.request.user return super(AddPost, self).form_valid(form) -
How do I get groups__name on a line in the Django user model query?
I want get groups__name in a line at User.objects.values('id', 'username', 'groups__name) But I get example: {'id': 1, 'groups__name': None, 'username': 'admin'}, {'id': 2, 'groups__name': 'Manager', 'username': 'test'}, {'id': 2, 'groups__name': 'Personal', 'username': 'test'} I want query like this example: {'id': 1, 'groups__name': None, 'username': 'admin'}, {'id': 2, 'groups__name': ('Manager', 'Personal'), 'username': 'test'} I use django 1.11 -
Django add a relation between the user and the selected articles
I have a simple model Article. The model is: class Article(models.Model): title = models.CharField() text = models.TextField() likes = models.IntegerField(default=0) user = models.ForeignKey(User) I have also login, and likes, every user has favorite articles. I make new model: class LikeArticle(models.Model): article = models.IntegerField() user = models.ForeignKey(User) In view we have def articleLike(request): if request.method == 'POST': article_id = request.POST['id'] article_like = LikeArticle( article=article_id, user=request.user ) article_like.save() And when we want to see all favorite articles def favorite(request): favorite_list = LikeArticle.objects.all() return render(request, 'article/favorite.html', {'articleList': favorite_list}) But now its return me id article and username, how I can filter and choose from Article.objects.all() Is my logic correct? Maybe I need to do everything differently? -
Using some Django view data in the <style> tag
In my django view, I am passing a variable called data to the template. This data contains a field called hex_code which I want to use in my css. I am trying to do it the following way: <style> #my-item { background-color: {{ data.hex_code }}; } </style> The hex code is a string in the format '#ffffff'. However, this method does not work. Any way to fix this? Please note the following things: I don't want to use Javascript unless I absolutely have to. I only want to call data.hex_code in the style tag in the Html, not in a separate Css file. Thanks! -
templatetag to display list on individual rows
I'm struggling to get my templatetag to work. I believe it's the syntax or the way i'm calling app_filters. Forgive me i'm learning web application development so if my logic is off please correct me. My goal is to pass a collection of check boxes on one template to a new one filtered at a different level report_id is the collection of each check box. I have an array in my view from my GET.getlist call below checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) print (checkedlist) print (reportlist) args = {'retreivecheckbox': checkedlist} return render(request,'accounts/requestaccess.html', args) When I print my array the console displays it correctly, this example is if there was two check boxes selected: ['88', '89'] <QuerySet ['Common Data Model Reconciliation Load', 'LEJR BPCI IV - ICS Baseline']> I've created the following templatetag called app_filters defined as: from django import template register = template.Library() @register.filter def get_list(querydict, itemToGet ): return querydict.getlist(itemToGet) Now i'm trying to get my template to display what's in my console but as individual rows/indexes dependent upon user selections. I'm told get_list will do that for me. I've also tried get_at_index. I.E. I want to see retreivecheckbox as 88 89 and … -
Ubuntu 17: Can't install mysqlclient
Trying to follow a Django tutorial but I cannot install mysqlclient. The tutorial claims that I can do so with the following command: pip install mysqlclient but this generates this error: Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-rrolctwh/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/tmp/pip-build-rrolctwh/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-rrolctwh/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-rrolctwh/mysqlclient/ I have the most up-to-date pip and virtualenv installed. I would like to be able to install mysqlclient so that I may continue with the tutorial.