Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Any way to filter serializer in filter_backends?
I want to filter a specific queryset returned from a filter in a filter_backends. The codebase is new to me so please bare with me if this is noobish. The Viewset is: class ActionPointViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = ActionPoint.objects.all() serializer_class = ActionPointSerializer pagination_class = T2FPagePagination permission_classes = (IsAdminUser,) filter_backends = (action_points.ActionPointSearchFilter, action_points.ActionPointSortFilter, action_points.ActionPointFilterBoxFilter) renderer_classes = (renderers.JSONRenderer, ActionPointCSVRenderer) lookup_url_kwarg = 'action_point_pk' def export(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = ActionPointExportSerializer(queryset, many=True, context=self.get_serializer_context()) response = Response(data=serializer.data, status=status.HTTP_200_OK) response['Content-Disposition'] = 'attachment; filename="ActionPointExport.csv"' return response The filter I want to change is the action_points.ActionPointFilterBoxFilter which looks like : class ActionPointFilterBoxFilter(BaseFilterBoxFilter): serializer_class = ActionPointFilterBoxSerializer with the ActionPointFilterBoxSerializer being: class ActionPointFilterBoxSerializer(serializers.Serializer): f_status = serializers.CharField(source='status', required=False) f_assigned_by = serializers.IntegerField(source='assigned_by__pk', required=False) f_person_responsible= serializers.IntegerField(source='person_responsible__pk', required=False) and BaseFilterBoxFilter being: class BaseFilterBoxFilter(BaseFilterBackend): """ Does the filtering based on the filter parameters coming from the frontend """ serializer_class = None def filter_queryset(self, request, queryset, view): data = self._get_filter_kwargs(request, queryset, view) # To have proper keys in data dict, the serializer renames the incoming values according to the needs return queryset.filter(**data) def _get_filter_kwargs(self, request, queryset, view): serializer = self.serializer_class(data=request.GET) if not serializer.is_valid(): return queryset return serializer.validated_data So the thing I am focusing on is in the ActionPointFilterBoxSerializer, when the url … -
Setting custom "authentication_form" does not render the custom form
I'm attempting to apply bootstrap to a django login form. I have scoured google for hours and pretty much everyone is saying the same thing, which is to set the custom authentication_form in urls.py, override the username and password fields in custom login form and pass the class through the widget's attrs parameter. I have done this but django still isn't applying the form-control class to my input fields. I'm not quite sure what is going wrong. The form still renders, but without applying the bootstrap styling. urls.py from django.conf.urls import url from django.contrib.auth.views import LoginView, LogoutView, PasswordChangeView, PasswordChangeDoneView, \ PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView from account.forms import LoginForm from account.views import dashboard urlpatterns = [ url(r'^$', dashboard, name='dashboard'), url(r'^login/$', LoginView.as_view(), {'authentication_form': LoginForm}, name='login'), url(r'^logout/$', LogoutView.as_view(), name='logout'), url(r'^password-change/$', PasswordChangeView.as_view(), name='password_change'), url(r'^password-change/done/$', PasswordChangeDoneView.as_view(), name='password_change_done'), url(r'^password-reset/$', PasswordResetView.as_view(), name='password_reset'), url(r'^password-reset/done/$', PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^password-reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A- Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^password-reset/complete/$', PasswordResetCompleteView.as_view(), name='password_reset_complete') ] forms.py from django.contrib.auth.forms import AuthenticationForm from django.forms import CharField, TextInput, PasswordInput class LoginForm(AuthenticationForm): username = CharField(widget=TextInput(attrs={'class': 'form- control'})) password = CharField(widget=PasswordInput(attrs={'class': 'form- control'})) views.py @login_required( redirect_field_name=reverse_lazy('login'), login_url=reverse_lazy('login')) def dashboard(request): return render(request, 'account/dashboard.html', {'section': 'dashboard'}) -
How to get computer serial number with python?
""" Hello Comunity You know how I can access from python the serial number of the pc, I know that with dmidecode in the terminal I can find it and I am doing tests, the main idea is to register in the DB connected to Django the machine that I use in a record of a table My_code.py """ import subprocess var = str(subprocess.call(['sudo', 'dmidecode', '-s', 'system-serial-number' ])) print var fo = open("datos.txt","wb") fo.write("%s" % var) fo.close() """ I also use a library but it does not work or I still do not understand how to use it well """ -
How to Store 24-hour military format time to Django Models in TimeField
I'm trying to store time in 24-hour format to Django models. I'm using TimeField in models. So far when trying to store time in standard 12-hour format it works. But when trying to store time in 24 hour format it no longer works and instead gives an error saying to give a valid time. Here's my code so far: My models remaining_session_credits = models.DateTimeField(blank=True, null=True) session_credits = models.DateTimeField(blank=True, null=True) My views data["remaining_session_credits"] = timedelta(hours=data.get("session_credits")) data.get("session_credits") here is an integer which I'm converting to hours. -
difficulty in adding image in a recommendation system
I tried to add image in the reviews page of my project.The data is loaded but the image is not updated in the page.It just shows a blank white box and nothing else.Could you please help to find the error. my models.py looks like this: class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) wine = models.ForeignKey(Wine) pub_date = models.DateTimeField('date published', null=True) user_name = models.CharField(max_length=100) comment = models.CharField(max_length=200) rating = models.IntegerField(choices=RATING_CHOICES) images = models.ImageField(null = True, blank=True) the code for reviews_list look like this: {% extends 'base.html' %} {% block title %} <h2>Latest reviews</h2> {% load static %} {% endblock %} {% block content %} {% if latest_review_list %} <div class="row"> {% for review in latest_review_list %} <div class="col-xs-6 col-lg-4"> <h4><a href="{% url 'reviews:review_detail' review.id %}"> {{ review.wine.name }} </a></h4> <br> <a><img src="{% static wine.images.url %}" height="200"></a> <h6>rated {{ review.rating }} of 5 by <a href="{% url 'reviews:user_review_list' review.user_name %}" >{{ review.user_name }}</a></h6> <p>{{ review.comment }}</p> </div> {% endfor %} </div> {% else %} <p>No reviews are available.</p> {% endif %} {% endblock %} the code for views.py look like this: from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.core.urlresolvers import … -
Do not print media from django form
I created a custom widget and included a Media class. class MyWidget(forms.MultiWidget): class Media: css = { 'all': ('path-to-css.css',), } js = ( 'path-to-js.js', ) def __init__(self, visible_input_attrs=None, hidden_input_attrs=None): widgets = ( TextInput(attrs=visible_input_attrs), HiddenInput(attrs=hidden_input_attrs), ) super(MyWidget, self).__init__(widgets) def decompress(self, value): if value: return ['', value] return [None, None] In my form I use this widget as follows class UserForm(forms.ModelForm): class Meta: model = User fields = [ 'first_name', 'last_name', 'email', 'phone_number', ] widgets = { 'phone_number': MyWidget(), } My template file {% extends "base.html" %} {% load static i18n crispy_forms_tags %} {% block content %} <div class="row"> <div class="col-sm-12"> <form id="my-form" action="" method="post" enctype="multipart/form-data"> <h2>Contact details</h2> {% crispy user_form %} </form> </div> </div> {% endblock content %} {% block javascript %} {{ block.super }} {{ user_form.media.js }} {% endblock %} In my template file I include the form with {% crispy user_form %} (using crispy forms). Django hereby automatically adds the CSS and JS files at the beginning of the form. Since I load JS files at the very end of every HTML page and since the included path-to-js.js file requires jQuery, I append {{ user_form.media.js }} to my javascript block in my template. As a consequence, path-to-js.js appears more … -
Django + Vue.js issue
I want to implement Vue.js at my Django project. Code: <html> <head> <meta charset="utf-8"> <script type="text/javascript" src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.min.js"></script> </head> <body> <div id="demo"> <p>{{message}}</p> </div> <script> var demo = new Vue({ el: '#demo', data: { message: 'Hello Vue.js!' } }); </script> </body> </html> Works everywhere except my django project. Any ideas ? -
How to use form fields in template in django
i need your help, i'm trying to implement sign up functionality in django but i didn't know how to connect the template form to my view. I'm using the following view : def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your blog account.' message = render_to_string('acc_active_email.html', { 'user':user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) # user.email_user(subject, message) toemail = form.cleaned_data.get('email') email = EmailMessage(subject, message, to=[toemail]) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = SignupForm() return render(request, 'signup.html', {'form': form}) And this is a part of the template i did : <div class="centre"> <h1>Register For An Account To Access Ultra Marker API</h1> <form class="form" method="post"> {% csrf_token %} <input type="text" class="name" placeholder="First Name", value={{ }} > <input type="text" class="name" placeholder="Last Name", value={{ }} > <input type="email" class="email" placeholder="Email", value={{ }} > <input type="text" class="name" placeholder="Username", value={{ }} > <input type="password"required autocomplete="off" placeholder="Password", value={{ }} /> <input type="password"required autocomplete="off" placeholder="Confirm Password" value={{ }} /> <input type="submit" class="submit" value="Register"> <br/> <br/> <div style="text-align: right;padding-right: 10px"> <a href="login/">Already registred ? Log in !</a> </div> </form> My forms.py: class SignupForm(UserCreationForm): email = forms.EmailField(max_length=254, … -
Copy a custom plugin across multiple django cms pages
I asked a related question here earlier (How to programmatically create and apply a django cms alias plugin) but i thought it best to ask a question with my main problem I'm trying to make a utility where, given a django cms plugin i could clone this across multiple pages upon "Saving" the plugin. Initially, i have no idea what pages to save it in so, given a list of django cms pages, i could select certain placeholders of pages and after selecting those pages and pressing some "Save" button, the plugin would be cloned across those placeholders. Any changes to the template plugin should reflect on the copies on the other pages I've been doing some reading and i found an old django cms package called djangocms-stacks (https://github.com/divio/djangocms-stacks) but trying to install and use this in django cms 3.1.0 was causing an error due to an import of a module in cms.admin.placeholder which doesn't exist anymore. Although i did find this stackoverflow post (reuse same django cms plugin instance) with a comment that says that this is part of django core already. There's also a comment there though that says that this is called a static placeholder but from … -
Django haystack searching for html tags returns all posts
I have a django app (blog) which I am trying to implement django haystack with elasticsearch. The problem that I am having is that when testing the search functionality by searching for <p> or <html> I don't expect any results, however it's returning all my posts. Here is what my app/models look like: blog/models.py class Posts(models.Model): title = models.CharField(max_length=200, unique=True) html_content = models.TextField(blank=True, null=True) markdown_content = models.TextField(blank=True, null=True) date_created = models.DateTimeField(auto_now=False, auto_now_add=True) last_updated = models.DateTimeField(auto_now=True, auto_now_add=False) tags = models.ManyToManyField(Tag, through='PostTags') def save(self, *args, **kwargs): self.html_content = markdown.markdown( self.markdown_content, ["markdown.extensions.extra", "codehilite"] ) super(Posts, self).save(*args, **kwargs blog/search_indexes.py from haystack import indexes from .models import Posts class PostsIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField( model_attr='text', document=True, use_template=True ) title = indexes.CharField(model_attr='title') markdown_content = indexes.CharField( model_attr='markdown_content', null=True, indexed=False ) html_content = indexes.CharField( model_attr='html_content', null=True, indexed=False ) def get_model(self): return Posts def index_queryset(self, using=None): return self.get_model().objects.all() Now I assume that when I search for <p> or <html> is returning all my posts because I am saving html tags in the database, am I wrong? If so, how can I specify to ignore any html tags? I have also tried to use indexes.ModelSearchIndex and exclude the field html_content and yet searching for html tags seems to return all … -
How to get user's input using django class based view
What I want to do: I want to update a graph created in a view according to the user's input (i.e., user types the date range for the graph and the template generate a new graph with updated values). I have a django view which already creates the graph with pre-defined values. Check the code below, it works fine. views.py class ComecandoView(TemplateView): def get_context_data(self, **kwargs): context = super(ComecandoView, self).get_context_data(**kwargs) lista_precos = [] lista_datas = [] for variacao in range(10500): lista_precos.append(rjson['dataset']['data'][variacao][4]) lista_datas.append(rjson['dataset']['data'][variacao][0]) # Create a trace trace = go.Scatter( y = lista_precos, x = lista_datas ) data = [trace] fig = go.Figure(data=data) div = opy.plot(fig, auto_open=False, output_type='div') context['graph'] = div return context template_name = 'comecando.html' What I want is for the user to be able to select a value from a combobox for example or type a value into a text field and after he clicks a button the value he typed will be available in my view so that I'll be able to generate a new graph with new values. What I've tried: views.py I added this method inside my class based view but didn't output as expected, I was only able to use the value of the form 'q' … -
How to serialize a MPTT family and keep it hierarchical?
Using DRF and Django-MPTT I'm able to serialize my model and keep it hierarchical using recursivity as below, while also solving N+1 problems: #serializers.py class RootSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() channel = serializers.ReadOnlyField(source='channel.name') def get_children(self, parent): queryset = parent.get_children() serialized_data = RootSerializer(queryset, many=True, read_only=True, context=self.context) return serialized_data.data class Meta: model = Category fields = ('name', 'slug', 'full_path', 'channel', 'children') #models.py class Category(MPTTModel): name = models.CharField(max_length=50, blank=False) channel = models.ForeignKey(Channel, null=False, blank=False) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) #views.py class CategoryUniqueViewSet(generics.ListAPIView): serializer_class = RootSerializer def get_queryset(self): slug = self.kwargs['channel_slug'] queryset = cache_tree_children(Category.objects.filter(channel__slug__iexact=slug).select_related('channel')) return queryset which returns something like: "name": "Books", "channel": "walmart", "children": [ { "name": "Computers", "channel": "walmart", "children": [ { "name": "Applications", "channel": "walmart", "children": [] }, { "name": "Programming", "channel": "walmart", "children": [] } ] }, { "name": "Foreign Literature", "channel": "walmart", "children": [] }, { "name": "National Literature", "channel": "walmart", "children": [ { "name": "Fiction Fantastic", "channel": "walmart", "children": [] }, ] } ] }, However, I'm not able to keep the same response structure when I only want to show a family of a given Category. I can retrieve it using django-mptt's category.get_family(), which generates a TreeQuerySet. However, if I pass it to my serializer above, … -
Find the last commit containing 'word1'
In a big django project, I remember we change 'word1' by 'word2', but I don't even know what is 'word2'. However, I know I could find it with 'word1'. In other words, I would like to find the commit where I changed 'word1' to 'word2'. How could I do such thing? How could I find the last commit with 'word1' -
Django File Upload Not Saving To Filesystem
When I upload the file I get a "POST /submit/ HTTP/1.1" 200 604. When I check to see if the file uploaded I can't find it. Setting File includes: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Models: from django.db import models class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) Forms: from django import forms from mysite.uploads.models import Document class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ['description', 'document'] Views: from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from mysite.uploads.models import Document from mysite.uploads.forms import DocumentForm def model_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect(reverse('uploadindex')) else: form = DocumentForm() return render(request, 'uploads/index.html', { 'form': form }) Urls: from django.conf.urls import url from mysite.uploads import views urlpatterns = [ url(r'^$', views.model_upload, name='uploadindex'), ] -
PayPal Integration Steps
So I'm new to integrating PayPal. I'm using Django for my site so I'm using the PayPal Python SDK though that probably doesn't matter. What are the steps to integrating with PayPal? How does the SDK know who to actually send the payments to? PayPal's interface is very confusing so I was hoping to get some help here and maybe help others who are struggling to understand their documentation. -
How to programmatically create and apply a django cms alias plugin
I have this requirement where a django cms plugin needs to be duplicated across multiple pages. I've been doing some research and I found that there is a "Create alias" option for a plugin (Clone plugin for Django-cms). When i tried it though, there's no paste option available in the placeholder menus and the clipboard isn't accessible from the menu. Is there a setting to enable these? I'm using django 3.1. Also, is there a way to programmatically create an alias plugin for a django cms plugin and apply this alias plugin to target placeholders? I couldn't find an example for this too. Thanks -
how to start celery flower as as daemon in RHEL?
Im trying to run flower as daemon. My flower.service file read as follows: [Unit] Description=Flower Service After=network.target [Service] Type=forking User=maas Group=maas PermissionsStartOnly=true ExecStart=/bin/flower --broker=amqp://oser000300// [Install] WantedBy=multi-user.target But when i start the service, it is giving error. //systemctl status flower.service * flower.service - Flower Service Loaded: loaded (/etc/systemd/system/flower.service; enabled; vendor preset: disabled) Active: failed (Result: timeout) since Mon 2017-07-10 20:25:59 UTC; 4min 38s ago Process: 49255 ExecStart=/bin/flower --broker=amqp://oser000300// (code=exited, status=0/SUCCESS) Connected to amqp://guest:**@oser000300:5672// flower.service start operation timed out. Terminating. SIGTERM detected, shutting down Failed to start Flower Service. Unit flower.service entered failed state. flower.service failed. -
django-allauth - Error during template rendering (/path/to/site-packages/allauth/templates/account/login.html, error at line 0)
I am having a lot of fun installing django-allauth with my django 1.10 website. I have followed the online tutorial here but - when I come to attempt to login by accessing /foobar/login, I get the following error (stacktrace below): ImportError at /foobar/login/ No module named 'path' Request Method: GET Request URL: http:/localhost:8000/foobar/login/ Django Version: 1.10.7 Exception Type: ImportError Exception Value: No module named 'path' Exception Location: /path/to/env/lib/python3.5/importlib/__init__.py in import_module, line 126 Python Executable: /path/to/env/bin/python Python Version: 3.5.2 Python Path: ['/path/to/project', '/path/to/env/lib/python35.zip', '/path/to/env/lib/python3.5', '/path/to/env/lib/python3.5/plat-x86_64-linux-gnu', '/path/to/env/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/path/to/env/lib/python3.5/site-packages'] Error during template rendering In template /path/to/env/lib/python3.5/site-packages/allauth/templates/account/login.html, error at line 0 No module named 'path' 1 {% extends "account/base.html" %} 2 3 {% load i18n %} 4 {% load account socialaccount %} 5 6 {% block head_title %}{% trans "Sign In" %}{% endblock %} 7 8 {% block content %} 9 10 <h1>{% trans "Sign In" %}</h1> What is the cause of this error, and how do I fix it? -
Long running background thread in Django model
I'm fairly new to Python and Django, so please let me know if there is a better way to do this. What I am trying to do is have each Device (which inherits from models.Model) kick off a long running background thread which constantly checks the health of that Device. However when I run my code, it does not seem to be executing like a daemon, as the server is sluggish and continually times out. This background thread will (in most cases) run the life of the program. Below is a simplified version of my code: class Device(models.Model): active = models.BooleanField(default=True) is_healthy = models.BooleanField(default=True) last_heartbeat = models.DateTimeField(null=True, blank=True) def __init__(self, *args, **kwargs): super(Device, self).__init__(*args, **kwargs) # start daemon thread that polls device's health thread = Thread(name='device_health_checker', target=self.health_checker()) thread.daemon = True thread.start() def health_checker(self): while self.active: if self.last_heartbeat is not None: time_since_last_heartbeat = timezone.now() - self.last_heartbeat self.is_healthy = False if time_since_last_heartbeat.total_seconds() >= 60 else True self.save() time.sleep(10) This seems like a very simple use of threading, but every time I search for solutions, the suggested approach is to use celery which seems like overkill to me. Is there a way to get this to work without the need for something like … -
django urlconf direct from root to included app logic
I've been trying to solve this problem for a while, but haven't been able to find a solution that works. Maybe someone can help point out a better method! I'm using my root urlconf to redirect two requests to an included app: url("^about/news/", include("kdi.urls", namespace="kdi")), url("^about/recognition/", include("kdi.urls", namespace="kdi")), And here is the kdi app's urlconf: url(r"^$", "kdi.views.news", name="news"), url(r"^$", "kdi.views.recog", name="recog"), It seemed smarter to use the more granular redirection from root ^about/news/ and ^about/recognition to the ^$ in the app's urlconf. This worked fine with only one pattern, but I'd like to scale it to work for both. Would something like directing ^about/ from root to the app where I could check for ^/news$ or ^/recognition$ in the kdi app be smarter? Would that also be able to use the root's catch-all ^ if no matches were made? Is it possible to check the request.path from the urlconf and then use an if statement to direct to the correct view? Or maybe use a name field in the root and then access via that name in the app's url patterns? Just having a little trouble working out the logic with this! -
Looping through CSV string in Django Template
So I have a variable that is a comma separated string ("val1,val2,val3") and I want to iterate through each element in a Django template like: {% for host in network.hosts %} <h3>{{host}}</h3> {% endfor %} In this case my csv variable is network.hosts and my expected result would be: val1 val2 val3 How would I go about doing this? -
ModuleNotFoundError: No module named 'models'
I have a very simple django app that I am attempting to deploy to heroku, but it keeps crashing. Everything works fine on my local machine, but not on heroku here is the error I am getting (cut to the relevant parts): File "/app/hello/admin.py", line 4, in <module> 2017-07-10T20:12:27.482194+00:00 app[web.1]: import models 2017-07-10T20:12:27.482195+00:00 app[web.1]: ModuleNotFoundError: No module named 'models' I am using the default Django directory structure: -python-getting-started --hello ---init.py ---admin.py (this is where the error is) ---models.py (this is the file i'm trying to import) ---tests.py ---views.py It works just fine on my local machine. Am I importing it wrong? I honestly don't even know where to start with this. I do not have any problems on any of my other Django projects hosted on Heroku, just this one. here is the relevant portion of admin.py that is throwing the error: from django.contrib import admin from django import forms import models # Register your models here. class BasicInfoCollectionForm(forms.ModelForm): class Meta(): model = models.VolunteerBasicInfo fields = ('removed for brevity') Any help would be greatly appreciated -
Use react to pass a xls file data to python/django
I am trying to read data from a xls or csv file and read the data into my django app. In my jsx, I handle file change as follow: this.handleFile = (e) => { const reader = new FileReader(); const file = e.target.files[0]; const file_path = e.target.value; reader.onload = (upload) => { this.setState({ file: file_path, data_uri: upload.target.result, filename: file.name, filetype: file.type }); }; if(file.type === "application/vnd.ms-excel") { reader.readAsBinaryString(file); } else if (file.type === "text/csv"){ reader.readAsText(file); } else { sweetAlert('Error!', 'Only csv and xls file allowed.', 'error'); } } Then in my python view/api I do it this way: file_type = self.request.data['filetype'] if file_type == 'text/csv': file_content = csv.reader( self.request.data['data_uri'].split('\n'), delimiter=',') next(file_content) summary = import_file( rows_of_data=file_content, client=self.request.user.staff.client ) elif file_type == 'application/vnd.ms-excel': file_content = get_data(self.request.data['data_uri']) next(file_content) summary = import_file( rows_of_data=file_content, client=self.request.user.staff.client ) The csv file import works fine, but the xls doesn't work. I get "no suitable library found" when I try to use pyexcel_xls.get_data. -
Loading http content on https domain
We have created a website which is served right now on heroku. This is the website like cryptic-bayou-93861. This website have a search bar on the navbar and I wanted to used freefind's search service for its function. This search result I receive from it are all over http server and heroku server is not loading it. These are the errors : I want them to work fine just like they work on localhost. What can I do? The app is django based and I tried google custom search but it didn't workout. -
Python Django OperationalError no such column model.id
When trying to access my model via the Admin webpage using Django, I get an Operational Error stating "no such column: model_name.id" I did my migrations and all but I am still getting the same error. I assume I am getting this error because I had to change the name of my model. Since, I had to delete my database and migrations and had to re migrate all of my changes. I originally got the error of not having a table built so I used some SQL to build the table and now I am stuck with a missing column under the name "id". Thanks in advance.