Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why showing ImportError: No module named markdownx when migrating in django...?
markdown module is installed,still this error shows when trying to migrate with the command python manage.py migrate i am trying to load project in remote.the project folder is loaded usin scp command -
Permission matching query does not exist in custom permission
try: user = User.objects.get(username = 'xyz') custom_permission = Permission.objects.get(codename='is_custom') user.user_permissions.add(custom_permission) user.save() print user.has_perm("is_custom") print user.has_perm('app.is_custom') user.get_all_permissions() except Exception as e: print(">>>>>",e) I have done this simple thing to check the user custom permission but it rises the exception DoesNotExist('Permission matching query does not exist.') what's wrong in this ?? -
Testing REST framework JWT Auth error
So i was trying to test out the django restframework authentication token, but i ran into this error when trying to retrieve the token. Invoke-WebRequest : A parameter cannot be found that matches parameter name 'X'. + CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand can someone explain to me what this means, and does anyone know the solution this is what i typed into the cmd: curl -X POST -d "username=(username)&password=(password)" (the url to token) Thanks -
Playing a GIF with Django
Trying to get a gif to play on a single page website i'm developing. For some reason it's not displaying or playing properly. I'm using Django with Python as a backend and just simple HTML with Bootstrap as a front end. Really appreciate the help. Here's the code. <div class="col-xs-6 nopadding full-screen force-full-screen dark videoplay-on-hover"> <div class="vertical-middle ignore-header center"> <h2 class="nobottommargin ls1 font-body">different.</h2> </div> <div class="video-wrap"> <video id="slide-video" poster="{% static 'img/videos/1.jpg'%}" preload="auto" loop muted> <source src="{% static 'img/videos/1.webm' %}" type='video/webm' /> <source src="{% static 'img/videos/1.mp4' %}" type='video/mp4' /> </video> <div class="video-overlay" style="background-color: rgba(0,0,0,0.2);"></div> </div> </div> When I use the {% static ...%} for images it works fine. I don't really understand why it would be different for webm or mp4 type files. Thanks in advance! -
Python sorting in list django rest fram work
"test1":[ { "usemember1":"mem", "name":"new1", "usemember2":"wan_l2", "config_name":"policy", "config_value":"newr", "id":2 }, { "usemember1":"non", "name":"newro", "usemember2":"tab", "config_name":"policy", "config_value":"rram", "id":3 }, { "usemember1":"waa", "name":"new333", "usemember2":"wand", "config_name":"policy", "config_value":"newro", "id":4 }, { "count":"2", "name":"newroad", "interval":"120", "up":"", "down":"", "rtt":"", "reliability":"rr", "timeout":"700", "track_ip":"123.147.258", "packet_loss":"", "config_name":"interface", "config_value":"newrm", "id":5 } ] In this list i need only set which contains "config_name" : "policy" i want only this data { "usemember1":"mem", "name":"new1", "usemember2":"wan_l2", "config_name":"policy", "config_value":"newr", "id":2 }, { "usemember1":"non", "name":"newro", "usemember2":"tab", "config_name":"policy", "config_value":"rram", "id":3 }, { "usemember1":"waa", "name":"new333", "usemember2":"wand", "config_name":"policy", "config_value":"newro", "id":4 } i want to filter only the set contains "config_name" : "policy". how to solve this help me out? i want to put this get method. I want to sort and give to the endpoint. what are the possible ways to do it? -
django-restframework detailview issue
Using django-rest-framework I trying to implement few simple APIs. Following is the code. Issues I am facing is: The products/(?P\d+)/ never executes the ProductsDetailView. I always get all the list of products irrespective usage of IDs in the URLs. But, when I remove the products/ from URLs, then I get the single product as response. But, unfortunately now I cannot have all the products, as the URL for that API is removed. I am not sure what wrong I am doing because of which this issue is happenning. Please help me. MODEL: class Product(models.Model): product_owner = models.ForeignKey(User, verbose_name='User') product_imported_via = models.CharField(max_length=200, default="0", null=False, choices=PRODUCT_IMPORT_SOURCE, verbose_name='Source of import') product_title = models.CharField(max_length=100, null=False, verbose_name='Product title') product_description = models.TextField(max_length=250, verbose_name='Product description') product_qty = models.IntegerField(verbose_name='Quantity') product_mrp = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='Maximum retail price') product_offer_price = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='Selling price') _product_discount_amount = models.FloatField(null=True, editable=False, verbose_name='Discount amount', db_column='product_discount_amount') _product_discount_percentage = models.IntegerField(null=True, editable=False, verbose_name='Disount percentage', db_column='product_discount_percentage') product_sku = models.CharField(max_length=100, null=False, unique=True, verbose_name='SKU',help_text='Enter Product Stock Keeping Unit') product_barcode = models.CharField(max_length=100, null=False, verbose_name='Barcode') archive = models.BooleanField(default=False) SERIALIZER: from rest_framework import serializers from .models import Product class ProductsSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id','product_title', 'product_description', 'product_qty', 'product_mrp', 'product_offer_price','product_discount_amount','product_discount_percentage', 'product_sku','product_barcode') VIEWS: from rest_framework.views import APIView from rest_framework.response import Response from … -
Print several documents when click button django
My question is about how to select several documents and print those documents. For example, I choose 3 documents and when I click print button, they will be open in new link and all documents must be on one page. And top of this page I will have print button. Each document I can get by unique doc_id, and sent document data in json format, I already wrote function to print single document, but I don't know how to open several documents on one page, it must be same? -
uWSGI downtime when restart
I have a problem with uwsgi everytime I restart the server when I have a code updates. When I restart the uwsgi using "sudo restart accounting", there's a small gap between stop and start instance that results to downtime and stops all the current request. When I try "sudo reload accounting", it works but my memory goes up (double). When I run the command "ps aux | grep accounting", it shows that I have 10 running processes (accounting.ini) instead of 5 and it freezes up my server when the memory hits the limit. accounting.ini I am running Django 1.9, nginx 1.4.6 and uwsgi 2.0.12 -
I wanna make a dictionary has user_id's key & all excel data
I wanna make a dictionary has user_id's key & all excel data . Excel is In views.py I wrote def try_to_int(arg): try: return int(arg) except: return arg def main(): book3 = xlrd.open_workbook('./data/excel1.xlsx') sheet3 = book3.sheet_by_index(0) data_dict = OrderedDict() tag_list = sheet3.row_values(0)[1:] for row_index in range(1, sheet3.nrows): row = sheet3.row_values(row_index)[1:] row = list(map(try_to_int, row)) data_dict[row_index] = OrderedDict(zip(tag_list, row)) print(data_dict) main() print(data_dict) is OrderedDict([(1, OrderedDict([('', ''), ('Ton', ''), ('0014500ab9Cd', '')])), (2, OrderedDict([('', ''), ('Tom', ''), ('0014500ab9Cd', '')])), (3, OrderedDict([('', ''), ('Tom', 'A'), ('0014500ab9Cd', '')]) It is not my ideal result. I wanna make a dictionary like dicts = { 0014500ab9Cd: { New York_A-a_under500: ○, New York_A-a_500-700: ○, ・・・・ New York_A-e_under500: ○, ・・・・ New York_C-b_upper700: ×, }, 0014500ab9Cd: { Chicago_A-a_under500: ○, Chicago_A-a_500-700: ○, ・・・・ }, } I do not have to get name data.How can I get my ideal dictionary?What should i write it? -
Django oembed URLs for embedded tweets
I have a list of a few hundred Twitter oembed URLs but I don't know how to implement the GET requests of a list of URLs in a view. -
Django Image Upload Javascript Preview in CreateView Form
I am using Django CreateView to upload user-submitted images. The image upload works well. However, I want the user to be able to preview the image before submitting. The javascript that shows the image preview will not work. The code looks good to me. And I think that it should work. But it doesn't. I am hoping a fresh set of eyes can see what I am missing. models.py class Image(models.Model): user = models.ForeignKey(User, related_name='images_created') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='images/%Y/%m/%d') description = models.CharField(max_length=255, blank=True, default='') created = models.DateField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(User, related_name='images_liked', blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Image, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('images:detail', kwargs={'slug': self.slug}) def __str__(self): return self.title views.py class CreateUserSubmittedImageView(LoginRequiredMixin, CreateView): model = Image form_class = UserSubmittedImageForm template_name = 'images/image_form.html' def form_valid(self, form): cd = form.cleaned_data image = form.save(commit=False) image.user = self.request.user image = cd['image'] return super(CreateUserSubmittedImageView, self).form_valid(form) forms.py class UserSubmittedImageForm(forms.ModelForm): class Meta: model = Image fields = ('image', 'title', 'description') widgets = { 'title': forms.TextInput(attrs={'placeholder': 'What do you want to call this image?'}), 'description': forms.TextInput(attrs={'placeholder': 'Enter description here'}), 'image': forms.FileInput(attrs={'id': 'uploadImage', 'name': 'myPhoto', 'onchange': 'PreviewImage', }), } template.html <div class="row"> <div … -
How to express 'one to many' views in django?
I have two tables like below. These are 'one(History.testinfoid) to many(Result.testinfoid)' relationship. (Result table is external database) class History(models.Model): # default database idx = models.AutoField(primary_key=True) scenario_id = models.ForeignKey(Scenario) executor = models.CharField(max_length=255) createdate = models.DateTimeField() testinfoid = models.IntegerField() class Result(models.Model): # external (Result.objects.using('external')) idx = models.AutoField(primary_key=True) testinfoid = models.ForeignKey(History, to_field='testinfoid') testresult = models.CharField(max_length=10) class Meta: unique_together = (('idx', 'testinfoid'),) So, i want to expression to count of 'testresult' field in Result table. It has some condition such as 'Pass' or 'Fail'. I want to express a count query set for each condition. like this.. {'idx':1, 'pass_count':10, 'fail_count':5, 'executor':'someone', ...} ... {'idx':10, 'pass_count':1, 'fail_count':10, 'executor':'someone', ...} Is it possible? -
Post data from django html to external API using json
I am trying to post data to an external API using django html in json format. Once I select the dropdown, and click submit, the data should be posted to an external API in json format. what would be the best procedure to do that. I have created a form and my views logic is below. This is the url, I am trying to post, 'http://netbox.com/devices'. base.html <label for="device_role" class="em-c-field__label">Device role</label> <select class="em-c-select em-c-select" id="file" placeholder="Placeholder">] {% for devicerole in deviceroles %} <optgroup> <option value="{{ devicerole }}" disabled="disabled" selected="selected">{{ devicerole }}</option> </optgroup> {% endfor %} </select> <button class="xys"> <span class"xyz" value="select">Submit<span> </button> forms.py class NameForm(forms.Form) device_roles = forms.CharField(label='device_role', max_length=100) views.py def device(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): payload = {'apikey' : apikey, 'device_role' : request.POST.get('device_role') response = request.get('http://netbox.com/devices', params=payload) else: form = Nameform() return render(request, "index.html", {'form': form} -
2 RabbitMQ workers and 2 Scrapyd daemons running on 2 local Ubuntu instances, in which one of the rabbitmq worker is not working
I am currently working on building "Scrapy spiders control panel" in which I am testing this existing solution available on [Distributed Multi-user Scrapy Spiders Control Panel] https://github.com/aaldaber/Distributed-Multi-User-Scrapy-System-with-a-Web-UI. I am trying to run this on my local Ubuntu Dev Machine but having issues with scrapd daemon. One of the Workers, linkgenerator is working but scraper as worker1 is not working. I can not figure out why scrapyd won't run on another local instance. Background Information about the configuration. The application comes bundled with Django, Scrapy, Pipeline for MongoDB (for saving the scraped items) and Scrapy scheduler for RabbitMQ (for distributing the links among workers). I have 2 local Ubuntu instances in which Django, MongoDB, Scrapyd daemon and RabbitMQ server running on Instance1. On another Scrapyd daemon is running on Instance2. RabbitMQ Workers: linkgenerator worker1 IP Configurations for Instances: IP For local Ubuntu Instance1: 192.168.0.101 IP for local Ubuntu Instance2: 192.168.0.106 List of tools used: MongoDB server RabbitMQ server Scrapy Scrapyd API One RabbitMQ linkgenerator worker (WorkerName: linkgenerator) server with Scrapy installed and running scrapyd daemon on local Ubuntu Instance1: 192.168.0.101 Another one RabbitMQ scraper worker (WorkerName: worker1) server with Scrapy installed and running scrapyd daemon on local Ubuntu Instance2: 192.168.0.106 Instance1: … -
Efficiently record and store page view counts in Django?
How can I count & store the Page views in Django? Please help me! -
Itinerary Not rendered With directionsDisplay.setDirections(result) in Javascript
I try to render an itinerary in Javascript using variable from a Django model. I can render a single Location but an itinerary... doesn't work... Basicaly I use the geocode function to convert my input address into geometry location but when I use these coordinates it doesn't show anything... Here is my code, if you can help me it will be great! <script> var directionsDisplay; var directionsService = new google.maps.DirectionsService(); var map; function initMap() { directionsDisplay = new google.maps.DirectionsRenderer(); var mapOptions = { zoom:12, center: {lat: 0, lng: 0}, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById('map'), mapOptions); directionsDisplay.setMap(map); var geostart = new google.maps.Geocoder(); var startpos; var start = document.getElementById('addrloc').value; geostart.geocode({'address': start}, function(results, status) { if (status === 'OK') { startpos = results[0].geometry.location; } else { alert('Address has not been found'); } }); var geoend = new google.maps.Geocoder(); var endpos; var end = document.getElementById('addrdest').value; geoend.geocode({'address': end}, function(results, status) { if (status === 'OK') { endpos = results[0].geometry.location; } else { alert('Address has not been found'); } }); var request = { origin: startpos, destination: endpos, travelMode: 'DRIVING' }; directionsService.route(request, function(result, status) { if (status == 'OK') { directionsDisplay.setDirections(result); } }); } </script> -
What Pieces of technology are required to make a website pull data from an API and then display the results? (Integration)
If I am trying to build a website where: User will input information into a website That information is then used as a variable to pull information from a public API The website will then display the information retrieved 3a. The information will be stored into an internal database to then run some statistics/calculation on in the future.. and also displayed on the website. What pieces of technology(php, html, ajax, django, ruby??)/what do I need to know to build this? I have some knowledge in python that can pull the information on my local computer, and do step 3a, but I don't have much experience in webdevelopment and know how everything is integrated. -
Requested setting DATABASES, but settings are not configured error in my Django project
I am attempting to change my database settings in my django project from sqlite3 to mysql. I edited the database object in my settings.py file : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Identity', 'USER' : 'root', 'PASSWORD': '' } } I ran django-admin dbshell and got this error : File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/conf/init.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I followed the instruction from this answer to use settings.configure() from django.conf import settings settings.configure() It returned this message : Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/conf/init.py", line 63, in configure raise RuntimeError('Settings already configured.') RuntimeError: Settings already configured. When I ran python3 manage.py shell it gives me this error : File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 28, in raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb' All I want to do is use mySql instead of sqlite db. How do I do this ? -
Python - Send email error connection timeout
I got this error message when my server trying to send an email to user. Error log message Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 177, in __call__ response = self.get_response(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 230, in get_response response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 284, in handle_uncaught_exception 'request': request File "/usr/lib64/python2.7/logging/__init__.py", line 1175, in error self._log(ERROR, msg, args, **kwargs) File "/usr/lib64/python2.7/logging/__init__.py", line 1268, in _log self.handle(record) File "/usr/lib64/python2.7/logging/__init__.py", line 1278, in handle self.callHandlers(record) File "/usr/lib64/python2.7/logging/__init__.py", line 1318, in callHandlers hdlr.handle(record) File "/usr/lib64/python2.7/logging/__init__.py", line 749, in handle self.emit(record) File "/usr/lib/python2.7/site-packages/django/utils/log.py", line 117, in emit self.send_mail(subject, message, fail_silently=True, html_message=html_message) File "/usr/lib/python2.7/site-packages/django/utils/log.py", line 120, in send_mail mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs) File "/usr/lib/python2.7/site-packages/django/core/mail/__init__.py", line 97, in mail_admins mail.send(fail_silently=fail_silently) File "/usr/lib/python2.7/site-packages/django/core/mail/message.py", line 292, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 100, in send_messages new_conn_created = self.open() File "/usr/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 58, in open self.connection = connection_class(self.host, self.port, **connection_params) File "/usr/lib64/python2.7/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib64/python2.7/smtplib.py", line 315, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib64/python2.7/smtplib.py", line 290, in _get_socket return socket.create_connection((host, port), timeout) File "/usr/lib64/python2.7/socket.py", line 571, in create_connection raise err socket.error: [Errno 110] Connection timed out [pid: 16437|app: 0|req: 71/132] 88.157.165.166 () {54 vars in … -
Django Filtering Search Results using GET
I would like to build a filter for my ListView, to further narrow down the search results. Currently, the user searches for services in their area and chooses between paid or free service (Using radio buttons). Forms.py class LocationForm(forms.Form): Place = forms.CharField(label='Place') Lat = forms.FloatField() Lng = forms.FloatField() CHOICES = [('Free', 'Paid'), ('Free', 'Paid')] Type = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) SearchRadius = forms.IntegerField() views.py def get_context_data(self, **kwargs): if self.request.method == 'GET': form = LocationForm(self.request.GET) if form.is_valid(): SearchPoint=Point(form.cleaned_data['Lng'],form.cleaned_data['Lat']) Radius = form.cleaned_data['SearchRadius'] Type = form.cleaned_data['Type'] else: form = LocationForm() SearchPoint=Point(0,0) Radius = 15 Type='Free' try: Type except: vt_filter = "'Free'=True" else: if Type == 'Free': vt_filter="'Free'=True" else: vt_filter="'Paid'=True" context = super(IndexView, self).get_context_data(**kwargs) res = Model.objects.filter(location__distance_lte= (SearchPoint, D(km=Radius)),vt_filter)\ .annotate(distance=Distance('location', SearchPoint))\ .order_by('distance') context['teacher_list'] = res context['form'] = form return context I wanted to add something similar to .filter('Free'=True) to further narrow down the results. In my Models.py, for the Model, I have Boolean fields for Free and Paid respectively. Free = models.BooleanField(default=True) Paid = models.BooleanField(default=False) It seems that vt_filter, which is the additional filter I want to run to distinguish between free and paid services doesn't work, and gives me error: too many values to unpack (expected 2) -
Trying to parse some json but i am getting a key error - Django
I have a request that I am sending to an API and i am getting a json format response. I want to grab items from the response that is being sent back but not getting anything out of it. I am getting an error with the keys that I am putting in to grab. From the response below, I want to grab values for specific keys within the response and save them in variables to eventually save them within my database. Here is the code that I have: def createUserSynapse(request): argss = { 'email': 'hello@synapsepay.com', 'phone_number': '555-555-5555', 'legal_name': 'Hello McHello', 'note': ':)', # optional 'supp_id': '123abc', # optional 'is_business': True, 'cip_tag': 1 } user = SynapseUser.create(clients, **argss) print(user.json) response = json.loads(user) if response: _id = response['_id'] name = response.client['name'] link = response._links.self['href'] cip = response.extra['cip_tag'] supp = response.extra['supp_id'] print(name) print(_id) print(link) print(cip) print(supp) here is a sample of the reply: { '_id':'..4e57', '_links':{ 'self':{ 'href':'https://uat-api.synapsefi.com/v3.1/users/..54e57' } }, 'client':{ 'id':'..26a34', 'name':'Charlie Brown LLC' }, 'doc_status':{ 'physical_doc':'MISSING|INVALID', 'virtual_doc':'MISSING|INVALID' }, 'documents':[ ], 'emails':[ ], 'extra':{ 'cip_tag':1, 'date_joined':1504774195147, 'extra_security':False, 'is_business':True, 'last_updated':1504774195147, 'public_note':None, 'supp_id':'123abc' }, 'is_hidden':False, 'legal_names':[ 'Hello McHello' ], 'logins':[ { 'email':'hello@synapsepay.com', 'scope':'READ_AND_WRITE' } ], 'permission':'UNVERIFIED', 'phone_numbers':[ '555-555-5555' ], 'photos':[ ], 'refresh_token':'refresh_..G8LPqF6' } And … -
Django sitemap without database?
I'm using from django.contrib.sitemaps.views import sitemap for a site that doesn't used a database, but I get: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. when trying to load the sitemap, as it relies on Django Sites Framework -
Change form field value in django, after __init__ but before cleaning
I want to reset the value of some fields in my django form to None, inside the __init__ method of my form. This is what I have so far: class MyFormForm(forms.ModelForm): class Meta: model = MyModel fields = ['field1', ...] field1 = forms.IntegerField(max_value=100) def __init__(self, *args, **kwargs): values_changed = kwargs.pop('values_changed', False) super(MyFormForm, self).__init__(*args, **kwargs) self.data = self.data.copy() if not values_changed: for field in self.fields: self.data[field] = None Unfortunately, when the form is displayed in my template, the value that has been POSTed is still in it. How do I get rid of the value, so that the change takes effect in the template, which renders the form? Things that don't work: Setting the initial parameter. Since there is a value present, it will be ignored Using cleaned values. The form is not cleaned at this stage, since it is not valid. Because of this cleaned_data does not exist I'm accessing the values like this: {{ form.field1.value|default_if_none:"Please enter." }} -
Override default queryset with using as_manager
Django documents state we can override default queryset using manager's get_queryset method. What if I user models.Queryset and as.manager method to avoid duplicate methods. How can I override default query? It seems get_queryset method of models.Queryset doesnt seems to work in this case. Thanks. -
Django - allowed hosts encryption
Is it possible to encrypt allowed hosts in django settings.py? I would like to give my app to someone and allow him to use it only on particular domain. What is the best way to achieve that?