Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create Page and set it's StreamField value programmatically?
I want to create a BlogPage programmatically in wagtail with setting it's StreamField value. I can set heading field. But getting AttributeError: 'unicode' object has no attribute 'source' when I try to set the paragraph field. I want to set an image too. This is my BlogPage model. models.py class BlogPage(Page): template = 'wagtail/test_page.html' author = models.CharField(max_length=255) date = models.DateField("Post date") body = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ]) content_panels = Page.content_panels + [ FieldPanel('author'), FieldPanel('date'), StreamFieldPanel('body'), ] this my code to create page by running this script. create_page.py new_image_page = BlogPage( title='Blog', slug='michael', author='michael', date='2017-12-13', body=[('heading','New Heading'), ('heading','New Heading 23232'), ('paragraph','My Paragraph')] ) directory_page = Page.objects.get(slug='home') directory_page.add_child(instance=new_image_page) revision = new_image_page.save_revision() revision.publish() new_image_page.save() -
I'm getting this error- ModuleNotFoundError: No module named 'mysite.core'. I'm using Python version 3.6.2 and Django version 1.11.7.
I'm trying to implement Social Login in Django. I have already installed social_auth_app_django with this command 'pip install social-auth-app-django'. And I have also added this installed app to the settings part. I'm getting the following error when I try to use (python manage.py migrate) command. ModuleNotFoundError: No module named 'mysite.core' Note:I'm using Python version 3.6.2 and Django version 1.11.7 -
Python, set log level in Django project, deployed with gunicorn and 4 workers
I recently met a logging issue about set logging level. I have a demo django project, which is to test set log level. below is the page. enter image description here The log will be written to /tmp/run.log. When I deploy it with gunicoryn + nginx(proxy static file), and has 4 gunicorn workes. Set log level only have effect to one of the workers. enter image description here enter image description here Above the two pictures, I set log level to ERROR, but only effect worker 74096. Here are some information and Django code. System Info: System: Centos 7.4 x64 Python: 2.7.5 Django: 1.11.2 Gunicorn: 19.7.1 Django logging config: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(filename)s:%(lineno)s] %(message)s' } }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 1024, 'backupCount': 5, 'filename': '/tmp/run.log', 'formatter': 'verbose' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' set log level function name = "django_docker" bind = "unix:/var/run/django_docker.sock" worker_class = "egg:meinheld#gunicorn_worker" #workers = multiprocessing.cpu_count() * 2 + 1 workers = 4 reload = True umask = 0002 user = 'nginx' group = 'nginx' accesslog = "/tmp/gunicorn.access.log" errorlog = "/tmp/gunicorn.error.log" raw_env = ["DJANGO_SETTINGS_MODULE=django_docker.settings"] chdir = " /home/user/workspace/django_docker/" … -
Error while trying to proxy request
I have a project with ionic in the frontend and django in the backend. I have following lines of proxies in my ionic.config.json { "name": "proxy-example", "app_id": "myIonicApp", "proxies": [ { "path": "/api/", "proxyUrl": "http://localhost:8000/" } ], "integrations": {}, "type": "ionic1", "watchPatterns": [ "scss/**/*", "www/**/*", "!www/lib/**/*", "!www/**/*.map" ] } When I try to run by ionic serve I am getting following error [ERROR] [HPM] Error occurred while trying to proxy request users/ from localhost:8100 to http://localhost:8000/ (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors) -
A news site: how to cope with images?
A news site. This is a sketch. Articles are going to be represented like this: article = forms.TextField() A template is only for the header, the footer and the sidebar. In the template there will be: {{ article | safe }} The article field will contain html. The editor will prepare an article in MS Word, and the front end specialist will prepare it for publication. The problem is: images may be inserted anywhere. Images will be with srcset like this: <img srcset="elva-fairy-320w.jpg 320w, elva-fairy-480w.jpg 480w, elva-fairy-800w.jpg 800w" sizes="(max-width: 320px) 280px, (max-width: 480px) 440px, 800px" src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy"> Images will be prepared by django-imagekit. The problem is the paths to the images. As far as I can understand, paths to the images are only available in templates. I'm wholeheartedly against hard coding paths. Could you tell me whether there is any solution to this problem? -
there is this (SYNTAX ERROR) in urls.py in main project folder. I am making a basic 1 app registration website
while trying to make a simple registration page i got this error when i ran the server by python manage.py runserver I got a syntax error urls.py:- from django.conf.urls import url,include from django.contrib import admin from basic_app import views urlpatterns = [ url(r'^$', views.index,name='index'), url(r'^admin/', admin.site.urls), url(r'^basic_app/', include('basic_app.urls'), ] the error is:- File"F:\Web_Development_With_Udemey\Django\part5\learning_users\ learning_users\urls.py", line 24 ] ^ SyntaxError: invalid syntax I have checked these files thoroughly many times! thanks I am using django 1.11.8 and python 3.5.4 with Anaconda3 P.S- I am learning. -
TemplateDoesNotExist at /test2/ .please help me with this
views.py name.html cannot be found from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import Get_name # Create your views here. def index(request): if request.method == 'POST': form = Get_name(request.POST) if form.is_valid(): return HttpResponseRedirect('/THANKS/') else: form = Get_name() return render(request,'name.html',{'from':form}) name.html:why python is not able to find my template;my template dir structure is test2/templates/test2/name.html <form action="/username/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> forms.py from django import forms class Get_name(forms.Form): user_name = forms.CharField(label='username',max_length='50') test2/urls.py from django.conf.urls import url from .import views urlpatterns=[ url(r'^$',views.index,name='index'), ] test1/urls.py from django.contrib import admin from django.conf.urls import url , include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test2/',include('test2.urls')), ] -
Django update view with user selected filter, possible be ajax?
I am a beginner and still learning how to update view based on user input. When a user selects speciality, city, last_name I would like the output to sort by that field. I am trying to do this without reloading but not sure if this possible. I would be happy in the short term just to get functionality to work. Any helpful would be awesome. Please advise. error 500: TypeError at /md/ expected string or bytes-like object js $(function(){ $(".options").click(function() { var filterby; filterby = $(this).attr("dvalue"); console.log('options start', filterby); $.ajax({ url : "/md/", type: 'POST', data: { "filterby" : filterby, "csrfmiddlewaretoken" : $("input[name=csrfmiddlewaretoken]").val() }, success: console.log("success"), dataType: "html", error: function(xhr, errmsg, err){ console.log(xhr.status + ': ' + xhr.responseText); } }); }); }); views.py def physicians(request): user = User; liked = False; args = {} filterby ='speciality' if request.method == 'POST': filterby = request.GET.get('filterby', None) print("filterby", filterby) args.update(csrf(request)) physicians = Physician.objects.all().order_by(filterby) page = request.GET.get('page', 1) paginator = Paginator(physicians, 10) try: physicians = paginator.page(page) except PageNotAnInteger: physicians = paginator.page(1) except EmptyPage: physicians = paginator.page(paginator.num_pages) physicians_liked = Voter.objects.filter(user=request.user).values_list('physician', flat=True) args['physicians'] = physicians args['physicians_liked'] = physicians_liked return render(request, 'physicians.html', args ) html <h3> Find You Favorite Doctors </h3> <table class="table"> <thead> <tr> <div class="row"> … -
Add a webcam snapshot as URL to from Django Using webcam.js
I need some help, to upload a snapshot taken from a webcam and attach the url to a form field (as a kind of profile picture) to then send the form and save everything using DJango. Im using webcam.js, but the way to upload is in php and i'm just starting with python so i'm confused to transform the code to python I got this code to take the snapshot. JS function configure(){ Webcam.set({ width: 320, height: 240, image_format: 'jpeg', jpeg_quality: 90 }); Webcam.attach( '#my_camera' ); } function take_snapshot() { // take snapshot and get image data Webcam.snap( function(data_uri) { // display results in page document.getElementById('results').innerHTML = '<img id="imageprev" src="'+data_uri+'"/>'; }); Webcam.reset(); } function saveSnap(){ var base64image = document.getElementById("imageprev").src; Webcam.upload( base64image, 'upload.php', function(code, text) { console.log('Save successfully'); }); } My idea is to put this on a Modal div so i could take the snapshot and then close the modal and when i close it, the URL of the snapshot will be placed in the form field, so i could submit it. I dunno if there is any other easy way or a lib from django to do this. greetings! -
Django URL appending to oneanother
I am having a problem understanding what is going on in Django. I created a delete function that supposedly deletes a record based on the DB record id. Upon deletion, I want to redirect to the same page I pressed the 'delete' button. However, when I look at the url in the browser, it now contains an appended version of the two views. I will show my code below for clarity: urls.py: url(r'entry/current/$', views.current_entry_list, name='current_entry_list'), url(r'^entry/create/$', views.create_entry_form_view, name='create_entry'), url(r'update/(?P<pk>\d+)/$', views.update_entry_view, name='update_entry'), url(r'delete/$', views.delete_entry_view, name='delete_entry'), View delete method: def delete_entry_view(request): if request.method == 'POST': id = request.POST['id'] Entry.objects.filter(id=id).delete() return redirect('entry/current/') View list records method: def current_entry_list(request): now = datetime.datetime.now() month = now.month current_entries = Entry.objects.filter(input_date__month=11).order_by('- input_date').all() for entry in current_entries: print(entry) paginator = Paginator(current_entries, 10) page = request.GET.get('page') try: current_entries = paginator.page(page) except PageNotAnInteger: current_entries = paginator.page(1) except EmptyPage: current_entries = paginator.page(paginator.num_pages) context = { 'current_entries': current_entries, 'current_month': month, } return render(request, 'finance/entry.html', context) Here is what my url in the browser looks like: 127.0.0.1:8000/finance/delete/entry/current/ Why does the redirected view url appends to the previous url? Is there anyway i can replace completely? -
python django serializers.serializer
table portfolio_sub_images field is id, sub_image, sub_image_explain_title, sub_image_explain, portfolio_id, portfolio_title_id table portfolio_sub_images_title field is id, title_image_name, title_image result = portfolio_sub_images.objects.all().filter(portfolio_id=pk).select_related('portfolio_title') data = serializers.serialize('json', result) data json value is [{"model": "portfolios.portfolio_sub_images", "pk": 12, "fields": {"portfolio": 2, "portfolio_title": 2, "sub_image_explain": "1234", "sub_image": "images/20171121/arr_down_black_n8I4mFn.png"}}, {"model": "portfolios.portfolio_sub_images", "pk": 13, "fields": {"portfolio": 2, "portfolio_title": 3, "sub_image_explain": "54", "sub_image": "images/20171121/arr_up_QBdHbye.png"}}] I want to get the field of the joined table portfolio_sub_images_title json help me! -
Django: Add CSS to a variable in template
I have a field in my model named "clientName" and in my template I have 2 CSS that I want to apply to that field. ColorText ColorField So. I color the text first, but when I try to color the box does not take CSS properties My example: <p class = "ColorText"> {{form.clientName.label}} </p> <p class = "ColorFiled"> {{form.clientName}} </p> I have already tried adding the CSS class in my form, but without success widgets = {'nameClient' : forms.Select(attrs={'class':'ColorFiled'}),} -
Django: can't access to a folder of template of specific application
I'm a newbie in Django, and I created a project "first pycharm" with structure like that: \firstpycharm | manage.py | views.py +---firstpycharm | | middleware.py | | models.py | | settings.py | | urls.py | | wsgi.py | | __init__.py | | | +---__pycache__ +---app | | models.py | | models.pyc | | urls.py | | views.py | +---migrations | +---static | | +---build | | +---images | | +---vendors | +---templates | | **\---app | | | base_site.html | | | base_site_bk.html | | | index.html | | | index2.html | | | index3.html | | | index_bk.html | | | invoice.html | | | level2.html | | | login.html | | | map.html | | | media_gallery.html | | | morisjs.html | | | other_charts.html | | | page_403.html | | | page_404.html | | | page_500.html | | | plain_page.html | | | pricing_tables.html | | | profile.html | | | projects.html | | | project_detail.html | | | sidebar.html | | | tables.html | | | tables_dynamic.html | | | top_navigation.html | | | typography.html | | | widgets.html | | | xx.html | | \---report | | audiance_overview.html** +---static | \---script +---staticfiles | \---admin | … -
Django ORM split the name and search
I have a model named Suburb. with one field called name. name of the suburb can be mulitple words say "East west country". I want all the records whose part words starts with given string. class Suburb(models.Model): name = models.CharField(_('suburb name'), blank=False, max_length=200) search_string = "we" # Give me all records whose part words starts with "search_string" Suburb.objects.filter(...) # with ignore case ??? Example ---------- 1) "East west one" 2) "We east two" 3) "North south three" result should be 1) and 2) I have a pythonic solution. but its performance is quite bad. Thanks in advance -
What is python alternate to war file in java?
Today we just tried to create a war file in python but did not get any solutions. Could you let me know why python is not supporting to create a war kind of file. Is this because python does not support web applications but django framework does? then is there a way to create WAR file using django? -
How to integrate telegram with webhook
I am unable to integrate telegram with web-hook on receiving health-checks alerts. How will I implement this? -
DRF - request.user returns AnonymousUser in APIView while logged in during api call from fetch
I've constructed a APIView as such: class CustomAPIView(APIView): def get(self, request, *args, **kwargs): if not request.user or not request.user.is_authenticated(): return Response("User not logged in", status=status.HTTP_403_FORBIDDEN) # Other stuff And in my html template I'm making a call to it using fetchAPI: fetch('/api/request/url/', {method: 'get'}) .then( // Process info ); I'm logged in through all this, but I'm always being greeted with a 403 response with the request.user variable in the APIView returning AnonymousUser. However, if I try and visit the api url manually everything works out right. Can someone point out what I'm missing? Thanks in advance. -
Django add value to hidden field inline formset
I am using Django 1.11. I am trying to add a value to a hidden field in an inline formset form. I have tried unsuccessfully inserting the hidden field value at various points of def get_context_data and def form_valid. The code I am using is as follows: views.py @method_decorator(login_required, name='dispatch') class DocumentCreate(CreateView): model = DocumentClient success_url = reverse_lazy('documents') form_class = DocumentForm def get_context_data(self, **kwargs): data = super(DocumentCreate, self).get_context_data(**kwargs) if self.request.POST: data['docform'] = DocumentFormSet(self.request.POST, self.request.FILES) else: data['docform'] = DocumentFormSet() return data def form_valid(self, form): context = self.get_context_data() docform = context['docform'] if docform.is_valid(): self.object = form.save() docform.instance = self.object docform.save() return HttpResponseRedirect('documents') else: return self.render_to_response(self.get_context_data(form=form)) forms.py class DocumentForm(ModelForm): class Meta: model = DocumentClient exclude = () widgets = { 'cnum': HiddenInput(), } def __init__(self, *args, **kwargs): super(DocumentForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields['cnum'].required = False class DocumentDetailForm(ModelForm): class Meta: model = DocumentDetail exclude = () widgets = { 'document_date': DateInput(), } def __init__(self, *args, **kwargs): super(DocumentDetailForm, self).__init__(*args, **kwargs) self.fields['document_description'].required = False DocumentFormSet = inlineformset_factory(DocumentClient, DocumentDetail, form=DocumentDetailForm, extra=10, can_delete=False) The hidden field 'cnum' is that what I am trying to insert a value for capturing in the model. Is anyone able to provide any guidance on how to acheive this? Any assistance … -
Django - Pass a variable from the Template to the Manager
I am building myself a little budgeting app. I am using this Manager: class AccountMonthlyManager(MonthlyCalculationManager): def transactions(self, date_str): date = get_this_month_and_year(date_str) entries = self.related_set().filter(date__month=date[0], date__year=date[1]).aggregate(total=Sum('amount')) return entries.get('amount', 0) along with this model: class Account(models.Model): begin = models.FloatField() weekly_change = models.FloatField() fixed_value = models.FloatField(null=True) income = models.BooleanField(default=False) monthly = AccountMonthlyManager() objects = models.Manager() I want to show the total from all the transactions for each account in the template kinda like this: {% for account in view.budget_accounts %} <tr class="dataLine budget" data-id="{{ account.id }}"> <td>{{ account.label }}</td> <td>{{ account.monthly.transactions }}</td> </tr> {% endfor %} However, the manager needs a the date string, which is in my url. http://localhost:8000/budgets/2017-12/ I'm looking for a way to accomplish this which doesn't involve me overloading my view with a lot of code for this single purpose. Right now, all I am doing is this: def budget_accounts(self): return Account.objects.filter(income=False, fixed_value=None) I need a way to get this url string back to the manager, so it can deliver the correct totals! -
SELECT typarray FROM pg_type WHERE typname = 'citext'
SELECT typarray FROM pg_type WHERE typname = 'citext' Why I am getting this query in django debug panel and what does it mean? Whenever I navigate to the new page, this query gets run as 1st then all others, same thing in the python shell using connection.queries command. I am using django 1.11 and postgres 9.6. -
Django Rest Framework AttributeError 'function' object has no attribute 'model' in router.register
I try my first Django API using Django Rest Framework. Everything was fine, but I change something and stuck in this AttributeError and don't understand what to do. my code looks like in tutorial and it is half past 4 am, I really need help. so, this is the callback python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/dev/test/demo/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/dev/test/demo/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/usr/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, … -
Processing payment in dynamic form wizard
In django SessionWizard view how would I go about dynamically adding two forms, representing checkout and a receipt view, if the user chooses an option in the previous form that marks it is a paid item. I tried extending the form list in post but this causes nothing to be rendered. Moreover, since this is session based is this not insecure, even using braintree, since it's dealing with card numbers, paypal, etcetera. I would like to achieve a wizard, for a streamlined flow, of choosing a plan -> filling out form -> if paid -> checkout / receipt. -
Django dynamic verbose name
I'm struggling to think about how to achieve this. What I want to do is have a series of questions (to represent a Likert table) in a CharField object like so: for a in range(1, 11): locals()['ATL' + str(a)] = models.PositiveIntegerField( choices=[ [1, 'Disagree Completely'], [2, 'Disagree Strongly'], [3, 'Disagree'], [4, 'Neutral'], [5, 'Agree'], [5, 'Agree Strongly'], [7, 'Agree Completely'], ], widget=widgets.RadioSelectHorizontal(), verbose_name = Constants.ATL_qu_list[a-1]) del a And then change the verbose name for the question depending on the question number (again, I know I'm not supposed to be using locals() to store variables). Is there an easier way of achieving a dynamic label though? Thanks! -
Django Error Reverse for 'url' not found. 'url is not a valid view function or pattern name
I'm working on Django and in a trouble with removing old urls. I've got seven pages(urls) in my present program but decided to make it simpler with only three pages(urls). Then I tried to remove them just by comment-out, but it just comes out with the error like Reverse for 'url name' not found. 'url name' is not a valid view function or pattern name. I'm not getting those unnecessary urls set in other pages, so it should be deleted without any problem. Here is a snap shot to go more in details. error image A page link is showing as an error origin, but the page is actually nothing to do with the deleted urls. Need your help! Thanks! -
How do I get get a model objects own ID for limit_choices_to?
How do I limit choices of a ForeignKey to Objects which have a ForeignKey to an object I also have a ForeignKey too? class ExtendedProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='extended_profile') dob = models.DateField(null=True, blank=True, verbose_name="date of birth") prefered_profile = models.ForeignKey('Trainer', on_delete=models.SET_NULL, null=True, blank=False, related_name='main_profiles', limit_choices_to={ 'owner' : ____ }) def __str__(self): return self.user.username def create_user_profile(sender, instance, created, **kwargs): if created: ExtendedProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) ExtendedProfile is an extension Django's own User Model so has a OneToOneField type ForeignKey. Trainer is a different model of a profile, where there may be more than one Trainer with the same ForeignKey (field name 'owner') to User. I'm basically trying to ensure that 'prefered_profile' can only be objects owned by the same user as ExtendedProfile is... How do I get a value of self on a model?