Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to execute join queries of MySQL in Django?
My SQL query which runs perfectly in terminal looks like this: select t.txid, t.from_address, t.to_address, t.value, t.timestamp, t.conformations, t.spent_flag,t.spent_txid from transaction_details t where t.to_address =(select distinct a.address from address_master a inner join panel_user p on a.user = p.user and a.user= "auxesis"); Now I tried using it in Django like this: sql = """ select t.txid, t.from_address, t.to_address,t.value, t.timestamp, t.conformations, t.spent_flag,t.spent_txid from transaction_details t where t.to_address =(select distinct a.address from address_master a inner join panel_user p on a.user = p.user and a.user= "%s" """),%(user) cursor.execute(sql) res = cursor.fetchall() But ya its not working. So any one please help me with it? -
Technology matching query does not exist - get_or_create
I'm making a populate script to transfer data from an external database to my django environment. I'm retrieving like 1.300 records from the external database, but at the second record it goes wrong. The first record will be created perfectly. I'm getting the error: base.models.DoesNotExist: Technology matching query does not exist. mdl, succeeded = Technology.objects.get_or_create( name=title, short_description=description, created_on=publish_date, edited_on=edit_date, supplier_id=company_id, is_active=is_hidden, ) I'm sure it's going wrong in here, cuz when I'm printing print(title) above this piece of code it will print it correctly and if I print it below this piece of code it returns nothing. Maybe, what I'm not expecting, that it could be something in this piece of code.(In my code it's right below the first piece of code. -
Loading angular data from another html template
Quite a newbie with angular and having trouble with integrating it with django and the form generator. I'm trying to display a form done through easyformgenerator. This form makes use of angular to show the data, and I'm trying to display everything through calling another html template. This is my button to call the function: <a onclick="viewResponse(this)" id="{{fbuilder.uuid}}" role="button" class="btn btn-success btn-sm pull-right"> <i class="fa fa-fw fa-plus"></i> New Response </a> My viewResponse function: function viewResponse(item) { var uuid = $(item).attr('id'); $.ajax({ url: "{% url 'employee:ajax-fresponse-new' %}", data: '&uuid=' + uuid + '&eid=' + employee, type: "GET", success: function(data) { console.log(data); $('#FormResponse').html(data); } }); } And this is the separate html file which I'm trying to load the data from the form: {% verbatim %} <div class="eda-form" ng-app="appDemo" ng-controller="demoController as demoCtrl" ng-cloak> <eda-easy-form-viewer eda-easy-form-viewer-data-model="demoCtrl.dataModel" eda-easy-form-viewer-easy-form-generator-fields-model="demoCtrl.fieldsModel" eda-easy-form-viewer-submit-form-event="demoCtrl.submitFormEvent(dataModelSubmitted)" eda-easy-form-viewer-cancel-form-event="demoCtrl.cancelFormEvent()"> </eda-easy-form-viewer> <div ng-if="demoCtrl.showDataModel" class="row"> <div class="col-md-12"> <pre> {{ demoCtrl.dataModel }} </pre> </div> </div> </div> {% endverbatim %} <script type="text/javascript"> (function(){ 'use strict'; angular .module('appDemo', [ 'eda.easyFormViewer' //injects easy form viewer ]) .config(function($httpProvider){ $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }) .controller('demoController', demoController); demoController.$inject = ['$http']; function demoController($http){ var demoCtrl = this; demoCtrl.showDataModel = false; demoCtrl.fieldsModel = testACompleteForm(); demoCtrl.submitFormEvent = submitFormEvent; function submitFormEvent(dataModelSubmitted){ debugger $http({ method: … -
Pylint - only for parts of the code
there' s a bigger django project where pylint or similar has never been used. It' d be a too huge task to make it for all the files, however the idea would be to control it only for the changed parts of the code (during git push). So, for instance there' s a bigger views.py with 900 lines, and we change one line in the def sth(request): section. In this case i' d like pylint to run only on this method. It' s doable to cut out the containing method, but it' d have many problem with the missing environment. I' d kindly read all suggestions regarding to how to achieve our goal (to have a pylinted code not at once but in parts). Many thanks. -
Unable to run geoserver and authentication error
What is the address to connect to geoserver? I tried with this address localhost:8080/geoserver, but the page does not exist and I can not connect. How do I know if geoserver has been installed? What is the python command to start geoserver?Screenshot of error -
Create another table when user profile table gets created with same ID
In my app i want to when a user profile is created, another table associated with the user profile id, gets created at the same time. I'm new to Django. I've tried to create the table after user.save() in my models.py and serializers.py, by finding the current user_id and then call create(owner=user_id) on the model object i want to create with user profile but it gives me list index out of range. class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'email', 'name', 'password', ) extra_kwargs = {'password' : {'write_only' : True}} def create(self, validated_data): '''Creates and returns new user.''' user = UserProfile( email=validated_data['email'], name=validated_data['name'], ) user.set_password(validated_data['password']) user.save() """here im trying to create the other tabel""" user_id = UserProfile.objects.filter(email='email').values('id')[0]['id'] UserSessions.objects.create(owner_id=user_id) return user In my model.py : class UserProfileManager(BaseUserManager): """Helps Django work with our custom user model.""" def create_user(self, email, name, password): """Create a new user profile object.""" if not email: raise ValueError('Users must have an email address son!') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save(using=self.db) return user class UserProfile(AbstractBaseUser, PermissionsMixin, models.Model): """Represent a user profile""" email = models.EmailField(max_length=20, unique=True) name = models.CharField(max_length=20) objects = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] In views.py : class UserProfileViewSet(viewsets.ModelViewSet): """Handles … -
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!