Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I emit the HTML of an external website in a Django template?
I want to get the contents of one of my pages on an external site, the HTML and all contents. If were in .NET I could use WebClient and retrieve the page, save it to a variable, and emit it in Razor. PHP can use cURL. How can I do that in a Django template? Do I need to create a Plugin that uses urllib? If it matters, I am using DjangoCMS. I searched and tried the Django http module. I have looked at the helper Django module for http and didn't see anything. I wasn't sure where to put urllib or requests, as in I do not know if what I am trying to do requires me to build a plugin or a custom template tag. I was hoping to know how to do it with either Python and Django's template language or just the template language, so I really do not want to do this in JavaScript, iframe, object, etc. -
Using multiselect widget for a ForeignKey field Django
Good day i seem to be lost in how i want to implement something. so here is how it goes ive got a carowner model class carowner(models.Model): ..... carowner = models.CharField(primary_key=True) and a cars model class car(models.Model): .... carowner_id = models.ForeignKey(carowner) it has a foreignkey cause each car can only have one carowner but a carowner can have many cars but i run into a situation where ive got a modelform class assigncarownertocar(forms.ModelForm): car= forms.ModelChoiceField(widget=MultipleSelect()) class Meta: model=carowner fields = [# all fields that are needed ] what i want to happen is when im creating a new carowner asigns him multiple cars in the same form from a queryset i provided when the modelform is initialized. so everything loads fine in the form. i see the list of cars but once i select one or more i get this 'Select a valid choice. 539421 is not one of the available choices. what i am asking is should i add the modelmultiplechoicefield to the model that holds the foreign key? cause right now i have it attached to the carowner model. i dont see documentation stating that this is wrong -
storing python list of dictionaries in redis receiving recursion error
I have the following list of dictionaries: podcasts = [{'title': "Podcast1", 'url': 'https://example.com\\n', 'created_at': 'Thu, 28 Dec 2017', 'duration': '00:30:34'}] I attempt to save this with django redis with the following: from django.core.cache import cache cache.set('podcasts', podcasts) I get the error: File "jobs.py", line 13, in handle cache.set('podcasts', podcasts) File "python3.6/site-packages/django_redis/cache.py", line 33, in _decorator return method(self, *args, **kwargs) File "python3.6/site-packages/django_redis/cache.py", line 68, in set return self.client.set(*args, **kwargs) File "python3.6/site-packages/django_redis/client/default.py", line 109, in set nvalue = self.encode(value) File "python3.6/site-packages/django_redis/client/default.py", line 329, in encode value = self._serializer.dumps(value) File "python3.6/site-packages/django_redis/serializers/pickle.py", line 33, in dumps return pickle.dumps(value, self._pickle_version) ** RecursionError: maximum recursion depth exceeded while calling a Python object ** -
Django ModelForm foreign key filtering
I'm trying to filter foreign key field selections in my model form, but form isn't working. My scripts: forms.py from django import forms from .models import Album, Song class SongCreateForm(forms.ModelForm): class Meta: model = Song fields = [ 'album', 'name', 'is_favorite' ] widgets = { 'album': forms.Select(attrs={'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), 'is_favorite': forms.CheckboxInput(attrs={'class': 'form-check-input'}), } def __init__(self, user, *args, **kwargs): super(SongCreateForm, self).__init__(*args, **kwargs) self.fields['album'].queryset = Album.objects.filter(owner=user) views.py from django.views.generic import CreateView class SongCreateView(CreateView): template_name = 'music/song_create.html' success_url = '/songs/' def get_form(self, form_class=None): form_class = SongCreateForm(user=self.request.user) return form_class I've tried to identify the problem in console and here is the result: from music.forms import SongCreateForm from music.models import Album from django.contrib.auth import get_user_model UserModel = get_user_model() user = UserModel.objects.get(pk=22) album = Album.objects.get(pk=1) song_form = SongCreateForm(user=user, album=album, name='something', is_favorite=True) Traceback (most recent call last): File "/home/elgin/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2910, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-8-e0507c59917a>", line 1, in <module> song_form = SongCreateForm(user=user, album=album, name='something', is_favorite=True) File "/home/elgin/Desktop/python/pycharm/django/muplay/music/forms.py", line 40, in __init__ super(SongCreateForm, self).__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'album' What am I doing wrong? -
With django-ckeditor how would I dynamically set CKEDITOR_FILENAME_GENERATOR based on app name?
I'd like to be able to have a custom CKEDITOR_FILENAME_GENERATOR for one particular app while also having a default for all other apps. My first though was to dynamically set by app name somehow. Would something like the following be possible: #settings.py ... def filename_generator(): fng = 'myproject.custom_filename' if app_name = "blog" #<<<--- how would I achieve something like this? fng = 'blog.custom_filename' return fng CKEDITOR_FILENAME_GENERATOR = filename_generator() ... -
object has no attribute ***_set
I'm writing an app to record and what clothes a user wears each day. A user logs in, a Checkin object is created, and then the user is sent to a page where they can click buttons to add what clothes they wore that day. When a user selects Jeans, it creates a Jeans object that references the User and the current Checkin. I want the Jeans button to disappear once it is selected. In the template I want to reference {% if not checkin.jeans_set.all %} Jeans Link {% endif %} checkin.jeans_set.all always evaluates to False when run in the template. I'm getting the error: 'Checkin' object has no attribute 'jeans_set' I can reference {{ request.user.checkin_set.all }} without issue in the template. class Checkin(models.Model): user = models.ForeignKey('auth.User') date = models.DateField(auto_now_add=True) description = models.CharField(max_length=40) class ClothesBase(models.Model): checkin = models.ForeignKey(Checkin, on_delete=models.CASCADE) user = models.ForeignKey('auth.User') class Meta: unique_together = ('user', 'checkin') class Jeans(ClothesBase): def __str__(self): return 'Jeans' class Shorts(ClothesBase): def __str__(self): return 'Shorts' -
Iterate through Django many-to-many set in the order model instances are added
I currently have a Django model that has a many-to-many-relationship: class Pool(models.Model): event = models.OneToOneField(Event) participants = models.ManyToManyField(Player, null=True) Participants are added in a specific order, and then at various times participants will be added and removed. For example, we add participants 1 through 7 in that order, and then remove participants 1 and 4, and then add participant 8. So the participant order by time they were added to Pool is: 2, 3, 5, 6, 7, 8 I want to be able to iterate through the participants in that same order. will pool.participant_set.all() return them in that order? If not, is there any in-build way to order by when participants were added to the Pool? -
Django email not working in production
I have normal forms not modelform where a user fills up the details and submits it. then the data from the form is cleaned and emailed, as the POST request. I have configured a gmail account and it worked fine in development stage however I'm not receiving any emails in production. 1.there is no error 2.seems like its working cos the redirect page is appearing after submission of the form.(if it fails then I should see a different redirected page) I have received no email whatsoever neither from my website nor google. EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'abcd@gmail.com' EMAIL_HOST_PASSWORD =********** EMAIL_PORT = 587 EMAIL_USE_TLS = True that's the setup in settings.py views.py subject = 'General Inquiry' from_email = settings.EMAIL_HOST_USER to_email = [email] contact_message = """ Name: {} Email: {} Phone: {} Region: {} Customer's Message: {}""" .format(name, email, phone,region, message) send_mail(subject, contact_message, from_email, to_email, fail_silently=True) return redirect('upload:contact') Am I missing out on something??? -
How to store env variables other than inside gunicorn.service for a Django project?
I tried putting all my environment variables for my Django project inside ~/.bash_profile and then use it in gunicorn.service with EnvironmentFile=/home/user/.bas... but with no luck. Eventually I had to put everything in ExecStart with -e in front of every variable, also with SECRET_KEY and everything in plain text. Is it safe, is it possible to access this externally or how else could I do this? -
Python 3 / Django 2, Passing a dictionary value to form field before saving
I'm trying to get my app to use a serial number, entered on a form, to compare to a dictionary and update a product field on a form before saving. Here's the details: Dictionary is two columns, 'Product Code', and 'Product' The first three digits of the Serial number entered on the form will match to the Product Code in the dictionary. Once the user submits the form, I want it to evaluate the serial number's first three digits, compare it to the dictionary keys, then change the 'product' form field to the dict['Product'] before saving the form. Here is my view: def create(request): #Page with input form to submit new records if request.method == 'POST': form = RecordForm(request.POST) if form.is_valid(): sn = request.POST.get('serial') with open('prodlist.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: if sn[0:2] in row['Product Code']: form.fields['product'].update = row['Product'] else: pass form.save() return HttpResponseRedirect('/tracker/all/') else: form = RecordForm() return render(request, 'tracker/form2.html', {'form': form}, RequestContext(request)) With this, I'm geting a key error for the 'product' piece. Is there a way to pass a value to a form field after it is submitted? -
json.loads isnt working with AJAX call
I have an AJAX function which sends an array to my Django Backend. This is the AJAX: function send(){ var set_name = $('#class_name').val(); //console.log(ids) //console.log(set_name) var url = window.location.pathname; $.ajax({ method: "POST", url: url, data: { 'set_name': set_name, 'student_ids': JSON.stringify(ids), }, dataType: 'json', success: function (data) { //location.href = data.url;//<--Redirect on success } }); } I am trying to convert the string that is being sent from the AJAX to a list, however json.loads() isnt working. This is the python: student_ids = request.POST.get('student_ids', None) students_ids = json.loads(student_ids) Thanks for any help -
Django: using an annotated aggregate in queryset update()
I've run into an interesting situation in a new app I've added to an existing project. My goal is to (using a Celery task) update many rows at once with a value that includes annotated aggregated values from foreign keyed objects. Here are some example models that I've used in previous questions: class Book(models.model): author = models.CharField() num_pages = models.IntegerField() num_chapters = models.IntegerField() class UserBookRead(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) user_book_stats = models.ForeignKey(UserBookStats) book = models.ForeignKey(Book) complete = models.BooleanField(default=False) pages_read = models.IntegerField() class UserBookStats(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) total_pages_read = models.IntegerField() I'm attempting to: Use the post_save signal from Book instances to update pages_read on related UserBookRead objects when a Book page count is updated. At the end of the signal, launch a background Celery task to roll up the pages_read from each UserBookRead which was updated, and update the total_pages_read on each related UserBookStats (This is where the problem occurs) I'm trying to be as lean as possible as far as number of queries- step 1 is complete and only requires a few queries for my actual use case, which seems acceptable for a signal handler, as long as those queries are optimized properly. Step 2 is more involved, hence the delegation … -
Django Rest Framework, display data from a table referenced with a foreign key
I got stuck a bit with a small problem when doing my school project, the problem is that I have an api with DRF and wanting to show my patient data "main table" shows them without problems but when I want to show other patient data in a different table (this table is this reference with a foreign key to Patient) I have not managed to obtain the patient data from this other table. I can not make my api send me the other patient data from the foreign key referenced to the patient, could you help me? models.py class Paciente(TimeStampedModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) udi = models.UUIDField(default=uuid.uuid4, editable=False) first_name = models.CharField('Nombre(s)', max_length=100) last_name = models.CharField('Apellidos', max_length=100) gender = models.CharField('Sexo', max_length=20, choices=GENDER_CHOICES) birth_day = models.DateField('Fecha de nacimiento', blank=True, null=True) phone_number = models.CharField('Número de telefono', max_length=13) civil_status = models.CharField('Estado civil', max_length=20, choices=CIVIL_STATUS_CHOICES) etc..... class Antecedentes(TimeStampedModel): """ Modelo de motivo y antecedentes de la enfermedad presentada en el momento de la consulta """ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE, null=True) motivo = models.TextField('Motivo de la consulta') antecedentes = models.TextField('Antecedentes de la enfermedad actual', blank=True, null=True) serializers.py class antecedenteSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source="user.username") class Meta: model = Antecedentes fields = ('paciente' ,'motivo', … -
django Inheriting from helper class
I wanted to make wallets for BTC and LTC coins in my models. But since most of the code will be same apart from the coin_name and tx_fees. So, I thought of making a helper class like this : Wallet class ( snippet ) class Wallet(models.Model): name = models.CharField(max_length=80, editable=False) trading_amt = models.FloatField(default=0, validators=[MinValueValidator(0.0), ]) wallet_amt = models.FloatField(default=0, validators=[MinValueValidator(0.0), ]) wallet_address = models.CharField(default='', blank=True, max_length=100) coin_name = '' <-- will it serve the purpose ? tx_fee = 0 <-- and this ? def __init__(self, coin_name, tx_fee): self.coin_name = coin_name self.tx_fee = tx_fee @transaction.atomic def moveToTrading(self, amount): if amount > self.wallet_amt: return "Insufficient balance" else: self.trading_amt += amount self.wallet_amt -= amount return True @transaction.atomic def withdraw(self, amount, withdrawal_wallet_addr): if amount > self.wallet_amt: return "Insufficient balance" else: # First check if withdrawal address entered by user is # correct, using wallet daemon , if not return error if check_wallet(withdrawal_wallet_addr, "btc"): # initiate checkout return initiate_checkout(withdrawal_wallet_addr, self.coin_name, self.tx_fee) else: return "Incorrect Wallet address" def save(self, *args, **kwargs): self.name = gen_random_string('btc_wallet') super(Wallet, self).save(*args, **kwargs) def deposit(self, amount): self.wallet_amt += amount def __unicode__(self): return self.name def __str__(self): return self.name The use of coin_name is only while creating wallet address name like this : _btc_wallet_<64 char … -
jquery popup dosent iterating for Models values in Django
Issue : Jquery Popup doesn't iterate for model values in Django application, only the last value from query set it popup for all button. QuerySet values which are rendering from model to template via views are as below: <QuerySet [<CheckList: Feeds (S/N/L)>, <CheckList: EU/NY feeds>, <CheckList: EPSCPORT Feeds>, <CheckList: 9:00 AM IST time should be compeleted>, <CheckList: PL fees>, <CheckList: LOAD job should be completed>, <CheckList: Check all FD job status>, <CheckList: Cut off job should be completed>, <CheckList: Do the Health checks>, <CheckList: Check the Statement generation>, <CheckList: Check Service now tickets>, <CheckList: Check application status>, <CheckList: Perform the ELT health checks>]> The home.html file looks like: {% include 'header.html' %} {% load static %} {% include 'snippets/external.js' %} {% include 'snippets/nav.html' %} <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <script type="text/javascript" src="http://rawgit.com/vitmalina/w2ui/master/dist/w2ui.min.js"></script> <link rel="stylesheet" type="text/css" href="http://rawgit.com/vitmalina/w2ui/master/dist/w2ui.min.css" /> <body> <!-- --> <table class="table"> <tr> <th>Expected Time</th> <th>SLA Time</th> <th>Application</th> <th>Check Discription</th> <th>Check Details</th> <th>Task Handle by</th> <th>Completed time</th> <th>Start Effort</th> <th>Status</th> </tr> </thead> <tbody> {% for i in query_set %} <tr> <td><small class="text-muted d-block">{{ i.expected_time }}</small></td> <td><small class="text-muted d-block">{{ i.sla_time }}</small></td> <td><small class="text-muted d-block">{{ i.app_name }}</small></td> <td><small class="text-muted d-block">{{ i.check_discription }}</small></td> <td class="align-middle"> <button class="w2ui-btn" onclick="popup()"> <img src="{% static "file.png" %}" alt=" width="30" height="30"/></button> … -
Select Option for a field not related to anything?
How would you handle a scenario with a floating inline table that is a dimension in a pre-existing database that doesn't relate to the user in anyway? The goal is to load this table into a select option in a template, then post a save to the database on a submit. So there will be a relationship from the request to Table 1 at a later point in my model, going from the Request model to the Table1 model. The model: class Table1(models.Model): field1 = models.CharField(db_column='Unit_Num', max_length=5, blank=True, null=True) field2 = models.CharField(db_column='Company_Code', max_length=1, blank=True, null=True) class Meta: managed = False db_table = 'Table1' The view i'm not sure about but i think it would be: table1 = Table1.objects.all() args = {'table1':table1} return render(request, 'accounts/profile.html', args) Now to populate the select I tried the following in my template but it just puts a bunch of empty boxes: {% for table in table1 %} <select table1select="Choose a Option..." class="chosen-select" multiple tabindex="4"> <option value="{{table1.select}}"></option> </select> {% endfor %} I'm guessing it's empty because there is no relationship to the User, but i just want to list every row in the database for field1. -
Django Model Form not saving to databased when filled out with AJAX data
I am trying to save data from an ajax call to the database by using a model form. I think the problem is that the form isnt valid, as test is printed when the code runs. This is the Post part of the class based view def post(self, request): set_name = request.POST.get('set_name', None) form = SetCreate(request.POST) if form.is_valid(): instance = form.save(commit = False) instance.name = set_name teacher = Teacher.objects.get(user = request.user) instance.teacher = teacher instance.save() else: print('test') This is the Form: class SetCreate(forms.ModelForm): class Meta: model = Set fields = ('name', 'teacher', 'students') This is the AJAX: function send(){ var set_name = $('#class_name').val(); //console.log(ids) //console.log(set_name) var url = window.location.pathname; ids = JSON.stringify(ids) $.ajax({ method: "POST", url: url, data: { 'set_name': set_name, 'student_ids': ids, }, dataType: 'json', success: function (data) { //location.href = data.url;//<--Redirect on success } }); } Thanks for the help! -
Loggers in django not printing with-out debug mode
I have been working with Django for around 3-6 weeks now and I have been trying to log data on requests to the console and once that works make it go to files once deployed. from django.shortcuts import render, redirect from django.contrib import auth import logging logger = logging.getLogger(__name__) def err_not_found(request): user = check_access(request) if user is None: return redirect("/") logger.info(user) logger.info("Testing this stuff.") return render(request, "404.html", { 'title': "Error", 'user': user }, status=404) That code works perfectly fine, in Debug mode on Django the loggers print but with Debug off, it doesn't. This is my LOGGING section of my Django settings.py file. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'console': { 'level': 'NOTSET', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'NOTSET', 'propagate': True, }, 'django.request': { 'handlers': ['console'], 'propagate': False, 'level': 'ERROR', }, } } My goal is to be able to do logger.info() or logger.error() with-in views and have it print to the console and then to a file after I configure it when going into a production environment. Django: 2.0.1 Python: 3.6.4 -
How to Debug Django's Javascript?
How do you debug Django's JAvascript using Visual Studio Code, Brackets, or Atom? The documentation for these editors only talks about Node.js on server side. -
boto3 mturk send_bonus error
When I try to send bonus via Boto3 regularly (but not always) the RequestError appears: Exception Type: RequestError Exception Value: An error occurred (RequestError) when calling the SendBonus operation: This user is not authorized to perform the requested operation. Exception Location: /Users/chapkovski/mynewotree/lib/python3.5/site-packages/botocore/client.py in _make_api_call, line 615 the code is the following: response = client.send_bonus( WorkerId=self.WorkerId, BonusAmount=str(form.cleaned_data['bonus_amount']), AssignmentId=self.AssignmentId, Reason=form.cleaned_data['reason'], ) Since it works sometimes, it seems that there is a certain maximum amount that can be sent as a bonus per day. I do it in Sandbox so definitely it is not a problem of lack of funds. Anyone else has encountered the similar issue? -
How to get every objects one at a time Django
Sorry if the question is confusing I'm not an english speaker Here is my def : @register.inclusion_tag('menu/home.html') def show_menu(): buttonname = Button.objects.all() return {'button': buttonname} Here is my home.html : {% for buttons in button %} <li class="nav-item"><a class="nav-link" href=""> <button class="btn" type="submit"><i class="fa fa-bullhorn" aria-hidden="true"></i> {{ button }} </button> </a></li> {% endfor %} The problem is that it display the queryset of all the buttons everytime. How do I display one object one at a time ? Thanks ! -
Caught up in a Type Error: __init__() takes 1 positional argument but 2 were given
I am following this particular tutorial (tutorial link) to get my dynamic formsets working. I encountered this error which I am not sure where is it originated from or how to resolve it. Can someone tell me what could be done to resolve it? Yes, I know that this is a repetitive question here in SO. I have gone through many of those answers, but could not figure it out in my case. View code: class ProfileList(ListView): model = Profile class ProfileFamilyMemberCreate(CreateView): model = Profile fields = ['first_name', 'last_name'] success_url = reverse_lazy('purchase_order') def get_context_data(self, **kwargs): data = super(ProfileFamilyMemberCreate, self).get_context_data(**kwargs) if self.request.POST: data['familymembers'] = FamilyMemberFormSet(self.request.POST) else: data['familymembers'] = FamilyMemberFormSet() return data def form_valid(self, form): context = self.get_context_data() familymembers = context['familymembers'] with transaction.atomic(): self.object = form.save() if familymembers.is_valid(): familymembers.instance = self.object familymembers.save() return super(ProfileFamilyMemberCreate, self).form_valid(form) -
Django-rest-framework update user from another user that does not work
I need to update a user from another user. But when I do serializer.save () it just does not save to the database. My user model: class User(AbstractBaseUser, PermissionsMixin): class Meta: db_table='empresa_user' email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(verbose_name='User first name', max_length=30, blank=False) last_name = models.CharField(verbose_name='User last name', max_length=30, blank=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) dt_criacao = models.DateTimeField(null=True, default=timezone.now) perfil = models.CharField(verbose_name='Perfil do usuário', max_length=1, blank=False, null=False, default='B') empresa = models.ForeignKey(Empresa, related_name='empresa', on_delete=models.DO_NOTHING, null=False, blank=False, verbose_name='Empresa') objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ('first_name', 'last_name') def get_full_name(self): return self.first_name +' '+ self.last_name def get_short_name(self): return self.first_name def __str__(self): return self.email My serializer: class UpdateUserPerfilSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = ('perfil', ) def validate_perfil(self, value): if value not in ('A', 'G', 'B', ): raise serializers.ValidationError("Perfil inválido") return value My view: @api_view(['PUT']) @permission_classes((permissions.IsAuthenticated,)) def put_user(request, pk): empresa = get_empresa(request.user) try: user = get_user_model().objects.get(empresa=empresa, pk=pk) except get_user_model().DoesNotExist: raise Http404 serializer = UpdateUserPerfilSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I'm making the call like this: curl -X PUT 'http://localhost:8080/empresa/usuario/15/' -H 'Authorization: JWT MY_TOKEN' -d '{"perfil":"B"}' And that is my response: {"perfil":"A"} -
Django SuccessMessageMixin and jQuery notification function
I need call my notify function when form will be submited CreateView class in my views.py Django class will send message as success_url to the template and i need to catch message and show with jquery function class VisitorCreateView(generic.CreateView): template_name = 'visitor_add.html' form_class = VisitorCreateViewForm success_url = reverse_lazy('visitor:visitor_add') def form_valid(self, form): messages.success(self.request, message='Successfully added') return super(VisitorCreateView, self).form_valid(form) Notify function function notify(from, align, icon, type, animIn, animOut){ $.notify({ icon: icon, title: 'Visitor', message: 'was successfully added', url: '' },{ element: 'body', type: type, allow_dismiss: true, placement: { from: from, align: align }, offset: { x: 20, y: 20 }, spacing: 10, z_index: 1031, delay: 2500, timer: 1000, url_target: '_blank', mouse_over: false, animate: { enter: animIn, exit: animOut }, template: '<div data-notify="container" class="alert alert-dismissible alert-{0} alert--notify" role="alert">' + '<span data-notify="icon"></span> ' + '<span data-notify="title">{1}</span> ' + '<span data-notify="message">{2}</span>' + '<div class="progress" data-notify="progressbar">' + '<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' + '</div>' + '<a href="{3}" target="{4}" data-notify="url"></a>' + '<button type="button" aria-hidden="true" data-notify="dismiss" class="close"><span>×</span></button>' + '</div>' }); } jquery event when form will be submited $('.notifications-demo > .btn').click(function(e){ //e.preventDefault(); var nFrom = $(this).attr('data-from'); var nAlign = $(this).attr('data-align'); var nIcons = $(this).attr('data-icon'); var nType = $(this).attr('data-type'); var nAnimIn = $(this).attr('data-animation-in'); var nAnimOut … -
error for ImportError: No module named 'PyQt4' in Django
I am working Django app I want to create graph in django view using plot When I import from matplotlib import pylab as plt it thorws an error as below File "/home/akashk/anaconda3/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/akashk/projects/tutorial/website/urls.py", line 3, in <module> from . import views File "/home/akashk/projects/tutorial/website/views.py", line 21, in <module> from matplotlib import pylab File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/pylab.py", line 274, in <module> from matplotlib.pyplot import * File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/pyplot.py", line 114, in <module> _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup globals(),locals(),[backend_name],0) File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt4agg.py", line 18, in <module> from .backend_qt5agg import FigureCanvasQTAggBase as _FigureCanvasQTAggBase File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5agg.py", line 15, in <module> from .backend_qt5 import QtCore File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5.py", line 31, in <module> from .qt_compat import QtCore, QtGui, QtWidgets, _getSaveFileName, __version__ File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/qt_compat.py", line 124, in <module> from PyQt4 import QtCore, QtGui ImportError: No module named 'PyQt4' I am having PyQt5 with latest version. How can I avoid calling module PyQt4 Thanks